C语言 反向链表



任务是反向链表,所以我构建链表,然后打印出来,然后所有的反向函数,然后第二次打印出来。然而,第二个打印是空的。我想这是指针的问题,有人能解释一下吗?谢谢。

void reverseLinkedList(struct node** head) {
    struct node* curr, *prev, *temp;
    curr = *head;
    prev = NULL;
    while (curr) {
        temp = prev;
        prev = curr;        
        curr = curr->next;
        prev = temp;
    }
    *head = prev;
}
struct node* buildLinkedList(int list[], int len) {
    struct node* head = NULL;
    struct node* tail = NULL;
    struct node* node;
    int i;
    for (i = 0; i < len; i++) {
        node = (struct node*) malloc(sizeof(struct node));
        node->data = list[i];
        node->next = NULL;
        if (!head) {
            head = node;
        } else {
            tail->next = node;
        }
        tail = node;
    }
    return head;
}
void printLinkedList(struct node** head) {
    struct node* s = *head;
    while(s) {
        printf("%dt", s->data);
        s = s->next;
    }
    printf("n");
}
int main() {
    int list [6] = {6,7,8,3,4,5};
    struct node* header = NULL;
    header = buildLinkedList(list, 6);
    printLinkedList(&header);
    reverseLinkedList(&header);
    printLinkedList(&header);
}
我从控制台得到的结果是:
6       7       8       3       4       5   

,其中第二个printLinkedList没有打印任何内容。想知道问题出在哪里。谢谢。

看看你的函数来反转列表

while (curr) {
     temp = prev;
     prev = curr;        
     curr = curr->next;
     prev = temp;  // <<-- this resets prev to what it was before.
}

你永远不会改变next指针,但你改变了prev两次。

相关内容

  • 没有找到相关文章

最新更新