从尾部反转双重链接列表

时间:2016-04-29 03:48:08

标签: c pointers reverse doubly-linked-list

我目前正在练习学校休息时的指针,下面我写了反转双重链表的方法,但是当我把它交给在线测试时,它失败了。

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循环有一个明显的错误,但我无法诊断错误。

2 个答案:

答案 0 :(得分:3)

我认为错误就在这里:

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;
}

答案 1 :(得分:1)

替换

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;
}