C-链表:如何保存';头部';在';临时工';所以我不';不要每次都要向后移动
如果我出于任何原因遍历我的链接列表,打印、排序等。。。我必须向后重新遍历它以重置头部。有更好的方法吗C-链表:如何保存';头部';在';临时工';所以我不';不要每次都要向后移动,c,string,linked-list,C,String,Linked List,如果我出于任何原因遍历我的链接列表,打印、排序等。。。我必须向后重新遍历它以重置头部。有更好的方法吗 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;
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;
}
}
无需为了遍历列表而修改原始头指针。获取一个临时节点指针(局部变量),用head指针初始化它,并将其用于遍历。这样就不会修改列表的原始头指针
void print_list(list * l) {
list_node *tmp = l->head;
while(tmp) {
printf("Word: %s\n", tmp->word);
tmp = tmp->next;
}
}
struct list\u node*node=l->head代码>。并且不要在仅用于打印的函数中更改l->head
(或列表的任何其他部分)。为什么只为遍历而修改head指针。取一个新的节点指针,用头指针初始化它。使用它遍历列表