2016-04-29 64 views
1

我目前正在练习指针在我的学校休息时间和下面我写的方法来扭转双向链表,但是当我把它交给在线测试时,它会失败。扭转双尾列表从尾到头

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

+0

在线测试给出了什么错误? – nobism

+0

'Node Node' - >'Node'或'Node * head' - >'Node Node * head' – BLUEPIXY

+0

这里是错误:错误的答案! 一些可能的错误: 1.您从该函数返回了NULL值。 2.您的逻辑存在问题 – Belphegor

回答

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

当我将count设置为1时,出现段错误; – Belphegor

+0

好吧,我的编辑应该修复段错误,希望:) – skearney

+0

请你给我解释当我设置count = 1时,我的loop seg错误怎么来的? – Belphegor

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