【发布时间】:2019-08-09 23:25:46
【问题描述】:
如果我出于任何原因遍历我的链表,打印、排序等...我必须重新向后遍历它以重置头部。有没有更好的方法来做到这一点?
struct list_node {
struct list_node *next;
struct list_node *prev;
char word[30];
int word_count;
};
typedef struct list_node list_node;
struct list {
struct list_node * head;
int size;
};
typedef struct list list;
void print_list(list * l) {
while(l->head) {
printf("Word: %s\n", l->head->word);
if(l->head->next != NULL)
l->head = l->head->next;
else
break;
}
//now i reverse traverse the list so I can call printlist again if needed
while(l->head) {
if(l->head->prev != NULL)
l->head = l->head->prev;
else
break;
}
}
【问题讨论】:
-
struct list_node *node = l->head;。并且不要在仅用于打印的函数中更改l->head(或列表的任何其他部分)。 -
你为什么要修改你的头指针只是为了遍历。取一个新的节点指针,用头指针初始化它。使用它来遍历列表
标签: c string linked-list