链表c++代码错误

linked list c++ code error

本文关键字:错误 代码 c++ 链表      更新时间:2023-10-16

我是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;
    }
}