繁体   English   中英

从尾到头颠倒双向链接列表

[英]Reverse a Doubly Linked List From Tail to Head

我目前正在学校放假时使用指针,下面我编写了一种方法来反转双向链表,但是当我将其交给在线测试时,它失败了。

Node* Reverse(Node *head)
{
    int count = 0;
    struct Node *ptr = head;

    // return head if NULL
    if (head == NULL) {
        return head;
    }
    // if the list is only the head, then the reverse is just the head... so nothing changes
    if((head->next == NULL && head->prev == NULL)){
        return head;
    }

    //Come here if previous if statements fail, traverse the list until I reach tail which will become the
    // new head
    while(ptr->next != NULL){
        ptr = ptr->next;
        count++;
    }
    head = ptr; // this is the new head    
    //starting from tail all the way to head swap the "prev" and "next" of each node 
    struct Node *temp = ptr->next;

    for(int i = 0; i<count; i++){
        ptr->next = ptr->prev;
        ptr->prev = temp;
        ptr=ptr->next;
        temp= ptr->next;
        //count--;
    }

    return head;
}

我意识到,当我从头到尾遍历列表时,反转列表可能会更聪明,但我认为这很无聊,因此我决定从尾到头进行反转。 我怀疑while循环或for循环中存在明显错误,但是我无法诊断该错误。

我认为错误在这里:

while(ptr->next != NULL){
    ptr = ptr->next;
    count++;
}

假设您的链表中有2个元素。 然后, while循环将仅迭代一次,而count将为1。当您进入for循环时,它也将仅迭代一次,这意味着您将正确地为新头重新分配指针,而不是第二个元素(以前是头)。

如果将count初始化为1而不是0,则它应正确反映链接列表中的元素数,并且for循环应正确执行。

编辑:您还必须稍微重构for循环,以免在列表末尾出现段错误:

Node* temp;

for (int i = 0; i < count; i++)
{
    temp = ptr->next;
    ptr->next = ptr->prev;
    ptr->prev = temp;
    ptr = ptr->next;
}

更换

for(int i = 0; i<count; i++){//i<count --> i<=count : Because Not counting last element
    ptr->next = ptr->prev;
    ptr->prev = temp;
    ptr=ptr->next;
    temp= ptr->next;//<-- bad
    //count--;
}

for(int i = 0; i <= count; i++){
    ptr->next = ptr->prev;
    ptr->prev = temp;
    temp = ptr;
    ptr = ptr->next;
}

要么

while(ptr){
    ptr->next = ptr->prev;
    ptr->prev = temp;
    temp = ptr;//next prev
    ptr = ptr->next;
}

暂无
暂无

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

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