[英]I am unable to reverse the given linked list with the following code. Can someone point out the error in the code?
I am unable to reverse the given linked list with the following code.我无法使用以下代码反转给定的链表。 Can someone point out the error in the code?有人可以指出代码中的错误吗?
#include<iostream>
using namespace std;
class Node{
public:
int data;
Node* next;
Node* prev;
Node(int d)
{
this->data=d;
this->next=NULL;
this->prev=NULL;
}
};
void insertathead(Node* &head,int d)
{
Node* temp= new Node(d);
temp->next=head;
head->prev=temp;
head=temp;
}
void insertattail(Node* &tail, int d)
{
Node* newnode=new Node(d);
newnode->prev=tail;
tail->next=newnode;
tail=newnode;
}
void insertatmiddle(Node* &head, int position, int d)
{
Node* temp=head;
Node* newnode=new Node(d);
int count=1;
while(count<position-1)
{
temp=temp->next;
count++;
}
newnode->prev=temp;
temp->next->prev=newnode->next;
newnode->next=temp->next;
temp->next=newnode;
}
void reverse(Node* &head)
{
Node* current=head;
Node* temp=NULL;
while(current!=NULL)
{
temp = current->prev;
current->prev = current->next;
current->next = temp;
current = current->prev;
}
head=temp->prev;
}
void display(Node* head)
{
Node* temp=head;
while(temp!=NULL)
{
cout<<temp->data<<" ";
temp=temp->next;
}
cout<<endl;
}
int main()
{
Node* node1=new Node(10);
Node* head=node1;
Node* tail=node1;
insertathead(head,11);
display(head);
insertathead(head,12);
display(head);
insertathead(head,13);
display(head);
insertathead(head,14);
display(head);
insertattail(tail,15);
display(head);
insertatmiddle(head,3,20);
display(head);
cout<<head->data<<endl;
cout<<tail->data<<endl;
reverse(head);
display(head);
return 0;
}
In this code, when I am commenting out the insertatmiddle function then the reverse function is able to reverse the linked list completely.在这段代码中,当我注释掉 insertatmiddle function 然后反向 function 能够完全反转链表。 But after adding a node in between, the reverse function reverses the linked list till that particular node only.但是在中间添加一个节点之后,反向 function 将链表反向直到仅该特定节点。 Can someone figure out the error in this case?有人可以找出这种情况下的错误吗?
In your code for insertatmiddle
在您的insertatmiddle
代码中
newnode->prev=temp;
temp->next->prev=newnode->next; // newnode->next is always NULL here
newnode->next=temp->next;
temp->next=newnode;
you've made a mistake.你犯了一个错误。 Try尝试
newnode->prev=temp;
newnode->next=temp->next;
temp->next->prev=newnode;
temp->next=newnode;
And by the way, if the code is for you, as long as you understand what you're doing, all good, but the way you implemented顺便说一句,如果代码适合你,只要你明白你在做什么,一切都很好,但你实现的方式
int count=1;
while(count<position-1) { ... }
baffles me a bit, since the link temp
which has the newnode
appended after itself is head
for position = 0
, 1
, and 2
, which I find very unusual.让我有点困惑,因为在其后附加了newnode
的链接temp
指向head
position = 0
、 1
和2
,我觉得这很不寻常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.