如何遍历C中的链表 [英] How to traverse a linked list in C
本文介绍了如何遍历C中的链表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想遍历C中的此链接列表(stoListItem)
这是我写的代码:
I want to traverse this linklist (stoListItem) in C
this is the code i have written:
typedef struct ListItem
{
char* pc_Serial_Number;
int n_Availability;
char* pc_Color;
char* pc_IPAddress;
struct ListItem *pstNextListItem;
} ListItem_t;
ListItem_t stoListItem;
ListItem_t *stoNext;
stoNext = &stoMVCIListItem;
if (stoNext !=0)
{
while (stoNext->pstNextListItem!= 0)
{
printf("\n Device (%d)", iMVCI_No);
printf("\n SerialNumber = %s \n Availability = %d"
"\n Colour = %s \n IP = %s",
stoListItem.pc_Serial_Number, stoListItem.n_Availability,
stoNext->pc_Color, stoNext->pc_IPAddress);
i_No++;
/*stoNext = stoNext->pstNextListItem;*/
stoNext = stoListItem.pstNextListItem;
}
i_No = 0;
}
请告诉我这是什么问题.为什么我无法从链接列表中获取正确的值
Please tell me what is wrong in this..Why iam not able to get the proper values from the linked list
推荐答案
Manfred的答案几乎是正确的.您只需要保留您的评论语句:
Manfred''s answer is almost correct. You just need to keep your commented statement:
stoNext = &stoMVCIListItem;
while (stoNext != 0)
{
printf("\n Device (%d)",iMVCI_No);
printf("\n SerialNumber = %s \n Availability = %d" "\n Colour = %s \n IP = %s",
stoNext->pc_Serial_Number,
stoNext->n_Availability,
stoNext->pc_Color,
stoNext->pc_IPAddress
);
i_No++;
//your commented statement was the correct one actually
//it updates current pointer to the next item in the list
stoNext = stoNext->pstNextListItem;
}
它应像这样阅读:
It should read more like this:
typedef struct ListItem
{
char* pc_Serial_Number;
int n_Availability;
char* pc_Color;
char* pc_IPAddress;
struct ListItem *pstNextListItem;
}ListItem_t;
ListItem_t stoListItem;
ListItem_t *stoNext;
stoNext = &stoMVCIListItem;
while (stoNext != 0)
{
printf("\n Device (%d)",iMVCI_No);
printf("\n SerialNumber = %s \n Availability = %d" "\n Colour = %s \n IP = %s",
stoNext->,pc_Serial_Number,
stoNext->n_Availability,
stoNext->pc_Color,
stoNext->pc_IPAddress
);
i_No++;
stoNext=stoNext->pstNextListItem;
}
i_No=0;
就这样! if块可以完全消除,并且所有必要的工作现在都在while循环中完成.
最好的问候,
-MRB
That''s all! The if block can be eliminated completely and all the nescessary work is now done in the while loop.
Best Regards,
-MRB
这篇关于如何遍历C中的链表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文