我尝试使用三个独立的函数在C ++上实现Linked List:
这是我在C ++中的代码:
#include<iostream>
#include<conio.h>
#include<stdlib.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* head;
void Print()
{
cout << "The List is:" ;
Node* temp = head;
while (temp -> next != NULL)
{
temp = temp -> next;
cout << " " << temp -> data;
}
}
void Delete(int n)
{
if ( n == 1 )
{
Node* temp = head;
head = temp -> next;
delete temp;
return;
}
Node* temp1 = head;
for(int i = 0; i < n-2; i++)
{
temp1 = temp1 -> next;
}
Node* temp2 = temp1 -> next;
temp1 -> next = temp2 -> next;
delete temp2;
}
void Insert(int x, int n)
{
Node* temp = new Node();
temp -> data = x;
temp -> next = NULL;
if ( n == 1 )
{
temp -> next = head;
head = temp;
return;
}
Node* temp1 = head;
for (int i = 0; i < n-2; i++)
{
temp1 = temp1 -> next;
}
temp -> next = temp1 -> next;
temp1 -> next = temp;
}
int main()
{
head = NULL;
Insert(2,1);
Insert(3,1);
Insert(99,3);
Insert(4,2);
Insert(5,3); // 3, 4, 5, 99, 2
Print(); // 1st call
Delete(2);
Delete(3); // 3,5,2
Print(); // 2nd call
return 0;
}
问题在于,根据我的配置,打印功能的第一次调用产生4,5,2,99而不是3,4,5,2,99。第二次调用显示5,99。
答案 0 :(得分:1)
问题在于你的打印功能,试试这个:
void Print()
{
cout << "The List is:";
Node* temp = head;
while (temp != NULL)
{
cout << " " << temp->data;
temp = temp->next;
}
}
你需要打印直到临时本身不是NULL
在C ++中,我建议使用nullptr
代替NULL
。
答案 1 :(得分:0)
while循环中的两行,在print函数中被反转。您正在将指针移动到下一个元素然后打印,因此您永远不会打印第一个元素。你的功能必须如下:
void Print()
{
cout << "The List is:" ;
Node* temp = head;
while (temp -> next != NULL)
{
cout << " " << temp -> data;
temp = temp -> next;
}
}