我試圖使用遞回來反轉鏈表,但是當我首先嘗試列印出鏈表的所有元素時,它按預期列印出元素,但在列印出最后一個元素后,它開始重復列印最后一個和倒數第二個元素. 我試圖除錯它,我認為問題是最后一個元素指向倒數第二個元素,它是否應該指向 NULL。我無法弄清楚我的代碼有什么問題,所以請幫助我。
示例 - 輸入 1,2,3,4,5,6
預期輸出 6,5,4,3,2,1
實際輸出 6,5,4,3,2,1,2,1,2 ...
#include<iostream>
using namespace std;
class node{
public:
int val;
node *next;
node(int val)
{
this->val = val;
this->next = NULL;
}
node(int val,node *next)
{
this->val= val;
this->next=next;
}
};
void insertAtTail(node *&head,int val){
node *n = new node(val);
if (head==NULL)
{
head = n;
return;
}
node *temp = head;
while (temp->next!=NULL)
{
temp = temp->next;
}
temp->next=n;
}
void display(node *head)
{
node *n = head;
while (n!=NULL)
{
cout << n->val << "->";
n = n->next;
}
cout << "NULL" << endl;
}
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
int main()
{
node *head = NULL;
insertAtTail(head,1);
insertAtTail(head,2);
insertAtTail(head,3);
insertAtTail(head,4);
insertAtTail(head,5);
insertAtTail(head,6);
display(head);
node *newhead = reverseRecursive(head);
display(newhead);
return 0;
}
uj5u.com熱心網友回復:
函式中存在錯誤reverseRecursive()。
線head->next == NULL;應該是head->next = NULL;
node* reverseRecursive(node *&head)
{
if (head == NULL || head->next==NULL)
{
return head;
}
node *nHead = reverseRecursive(head->next);
head->next->next = head;
head->next == NULL; // <<< should be head->next = NULL;
return nHead; // 1->2->3->4->5->6->NULL
}
不確定您使用的是哪個編譯器,但此陳述句通常會生成警告。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/408324.html
標籤:
上一篇:如何確定指標指向的地址?(理論)
