链表实现-使用单独的Insert(), Delete(), Print()函数
Linked List Implementation - using separate Insert(), Delete(), Print() functions
我试图通过利用三个独立的函数在c++上实现链表:
- Insert(int x, int n) -获取要插入的数字(x)和要插入的位置(n),从位置1开始。
- Delete(int n) -删除从位置1开始的位置(n)上的数字;
- Print() -打印链表中的元素。
下面是我的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;
}
问题是,根据我的配置,第一次调用print函数产生4,5,2,99,而不是3,4,5,2,99。第二个呼叫显示5,99。
问题出在你的打印函数中,试试这个:
void Print()
{
cout << "The List is:";
Node* temp = head;
while (temp != NULL)
{
cout << " " << temp->data;
temp = temp->next;
}
}
你需要打印直到temp本身不是NULL
。
在c++中,我建议使用nullptr
而不是NULL
。
在print函数中,while循环中的两行是颠倒的。您将指针移动到下一个元素,然后打印,因此您永远不会打印第一个元素。你的函数必须像这样:
void Print()
{
cout << "The List is:" ;
Node* temp = head;
while (temp -> next != NULL)
{
cout << " " << temp -> data;
temp = temp -> next;
}
}
相关文章:
- 析构函数和'delete'之间的区别
- 析构函数中的"delete this"
- 析构函数是否会自动调用 delete[] C++?
- 将复制构造函数设置为private和=delete有什么区别
- 在析构函数中调用"delete"运算符时"compiler is out of heap space"编译器错误
- 继承 =delete 函数
- new[] / delete[] 并在C++中抛出构造函数/析构函数
- 我们什么时候应该在 C++ 中将析构函数声明为 =DELETE
- 在析构函数中使用 delete[]:为 RtlValidateHeap 指定的地址无效
- 将复制构造函数超载与DELETE,然后调用C 子类的默认构造函数
- delete[]调用析构函数时出现内存错误
- 我应该在函数中使用 delete[] 吗?
- 虚拟析构函数和delete关键字
- Delete导致基类中的虚拟析构函数出现内存错误
- c++析构函数调用一个delete运算符
- 将 delete 作为运算符或函数调用是否有任何区别
- 析构函数调用delete函数时程序崩溃
- delete[]函数在C++中无法正常工作
- std::unique_ptr<T[]> 使用派生对象数组,使用 delete 函数
- 如何对类对象使用delete函数