链表c++代码错误
linked list c++ code error
我是C++的新手。我已经为链表编写了一个C++代码。在eclipse中运行代码后,我收到一条错误消息,上面写着"linkedlist.exe已停止工作"。有人能告诉我哪里出了问题吗。在代码中,我创建了一个链表,并在其中插入了几个值。然后我写了一个语句来打印元素。
#include<iostream>
#include<cstdlib>
using namespace std;
struct Node
{
int data;
Node* P;
};
Node* H;
void Insert(int data)
{
Node* temp=new Node();
temp->data=data;
temp->P=NULL;
Node* temp1=H;
while(temp1->P!=NULL)
{
temp1=temp1->P;
}
temp1->P=temp;
}
int main()
{
cout<<"linked list"<<endl;
Insert(1);
Insert(2);
Insert(3);
Node* Print=H;
while(Print!=NULL)
{
cout<<Print->data<<endl;
}
}
// Initialize H.
Node* H = NULL;
void Insert(int data)
{
Node* temp=new Node();
temp->data=data;
temp->P=NULL;
// If there is nothing in the list, make the new Node the head.
if ( H == NULL )
{
H = temp;
}
else
{
Node* temp1=H;
while(temp1->P!=NULL)
{
temp1=temp1->P;
}
temp1->P=temp;
}
}
更新
打印列表的while
触发器需要为:
while(Print!=NULL)
{
cout<<Print->data<<endl;
Print = Print->P; // Missing in your code.
}
首先,为变量提供更好的名称。例如,Node* P
没有意义,你可以把它命名为next, prev
或任何你想让你和其他人理解的名字。您还可以查看命名约定
其次,我认为insert
不起作用。你是想插入到第一个、结尾还是某个位置。我会写这样的东西:
void insert(int val, int pos){
Node newNode = null;
newNode -> data = val;
Node temp = H;
if(pos<0){
H = newNode;
H->P = temp;
}
else{
for(int i = 0; i < pos; i++){
if(temp->P != null)
temp = temp->P
else break;
}
//I found the position of the element you supposed to insert
//You insert the element properly.
//Make sure that you link the next element to newNode;
}
}
你可以从这个页面学习插入
最后,您的打印输出总是检查第一个元素。If Print->data != null
,您将始终打印列表的第一个元素。
感谢大家的帮助。我写了以下内容,效果很好。这是一个链接列表代码,用于在列表末尾插入数据值。
#include<iostream>
#include<cstdlib>
using namespace std;
struct Node
{
int data;
Node* next;
};
Node* Head;
void Insert(int data)
{
Node* temp=new Node();
temp->data=data;
temp->next=NULL;
if(Head==NULL)
{
Head=temp;
return;
}
Node* temp1=Head;
while(temp1->next!=NULL)
{
temp1=temp1->next;
}
temp1->next=temp;
}
int main()
{
Head=NULL;
cout<<"linked list"<<endl;
Insert(1);
Insert(2);
Insert(3);
Node* Print=Head;
while(Print!=NULL)
{
cout<<"data=" <<Print->data<<endl;
Print=Print->next;
}
}
相关文章:
- 错误处理.将系统错误代码映射到泛型
- 为什么我在使用void函数时得到错误代码C2276
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- 逻辑运算符上出现错误代码 a')'
- 'val' Arduino 错误代码之前的预期'('
- 我在贪吃蛇游戏中收到了错误代码 -1073741571
- 根据 GetLastError 直接写入磁盘会导致错误代码 5
- 当我选择大于 720 的矩阵大小时,程序退出并显示错误代码.可能是什么原因?
- 创建进程 API 失败,在窗口 122 上出现错误代码 10
- 使用另一个函数调用一个函数(都在类中)时出现问题.没有错误代码C++
- 当命令失败时,gzip 会在 C++ 中返回错误代码吗?
- 从 C++ 调用 cURL 命令会返回意外的错误代码,如 1792 和 6656
- WSALookupServiceBegin() 上的错误代码 10022(无效的 arugment)
- C++ Schannel POST 400 错误代码错误请求
- openCL-创建子缓冲区返回错误代码13
- 更新了Runge-Kutta(RK4)C++错误代码中的二阶DE
- 获取有关使用未初始化内存的错误代码
- 排序程序的意外错误代码
- 正在将DJI错误代码记录到流中
- 来自API的错误代码..处理什么是好的做法