【问题标题】:C-Linked-List: How do I save the 'Head' in a 'Temp' var so I don't have to traverse backwards each timeC-Linked-List:如何将“Head”保存在“Temp”变量中,这样我就不必每次都向后遍历
【发布时间】: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


【解决方案1】:

不需要为了遍历链表而修改原来的头指针。取一个临时节点指针(局部变量),用头指针初始化它并使用它进行遍历。这样你就不会修改列表的原始头指针

  void print_list(list * l) {

        list_node *tmp = l->head; 

        while(tmp) {
            printf("Word: %s\n", tmp->word);
            tmp = tmp->next;
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-26
    • 2022-01-03
    • 2021-12-31
    相关资源
    最近更新 更多