Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C-链表:如何保存';头部';在';临时工';所以我不';不要每次都要向后移动_C_String_Linked List - Fatal编程技术网

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指针。取一个新的节点指针,用头指针初始化它。使用它遍历列表