简体   繁体   English

反向链接列表

[英]Reverse a linked list

The task is to reverse a linked list, so I build the linked list, then print is out, then all the reverse function, then print it our second time. 任务是反转链表,因此我建立了链表,然后打印出来,然后执行所有反向功能,然后第二次打印。 However, the second print is empty. 但是,第二张纸是空的。 I think it is pointer issues here, any one can explain? 我认为这是指针问题,任何人都可以解释吗? thanks. 谢谢。

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("%d\t", 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);

}

The result I get from console is: 我从控制台获得的结果是:

6       7       8       3       4       5   

where the second printLinkedList is printing nothing. 第二个printLinkedList不在打印任何内容。 Wondering where is the problem. 想知道问题出在哪里。 Thanks. 谢谢。

Looking at your function to reverse the list you have 查看您的功能以反转您拥有的列表

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

you never change the next pointer, but you change prev twice. 您永远不会更改next指针,但会更改两次prev

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM