在链表的末尾添加一个节点

adding a node at the end of a linked list

本文关键字:一个 节点 添加 链表      更新时间:2023-10-16

我对将新节点添加到链接它的程序有点停滞不前,它应该添加到列表的末尾,但我尽我所能,但仍然有一个解决方案,希望你们中的任何人可以帮助我提前感谢;

这是一段代码

   #include <iostream>
   using namespace std;

  struct node {
        int data;
        node* next;
              };
        node* head;
       void insert(int x);
       void numInsert();
       void numSearch();
     int main()
    {
     head=NULL;
int x,n;
cout <<"How many number? n";
cin >>n;
for (int i=0; i<n; i++){
    cout <<"Enter Number n";
    cin >> x;

}

node* newNode;
newNode = new node();
newNode->data=x;
newNode->next=head;
head=newNode;
/*
NewNode->next=NULL;
if (head !=NULL){
    NewNode->next=head;
}
else{
    head=NewNode;
}*/

     int num;
     cout<<"what number do you want to insert in the list n";
     cin>>num;
     node *nNode;
     nNode = new node();
     nNode->data=num;
     nNode->next=NULL;
     node *prevNode;
     node *currNode;
     prevNode=NULL;
     currNode=NULL;
    {
     node* nNode= new node;
     nNode->data= num;
     nNode->next= NULL;
     currNode=NULL; prevNode=NULL;
    for(currNode=head; currNode != NULL; currNode= currNode->next)
    {
    if (newNode->data <= currNode->data)
    {
        break;
    }
    prevNode = currNode;
    }
    newNode->next=prevNode->next;
    prevNode->next=newNode;
    }
    return 0;
    }
每当我运行它时,到达

一个点并停止工作,请帮助我,作业今天到期,我不知道如何正确解决它

#include <iostream>
using namespace std;
struct node {
int data;
        node* next;
};
    node* head;
    node* tail;
    void insert(int x);
    void numInsert();
    void numSearch();
    int main()
    {
    head=NULL;
    tail = NULL;
    int x,n;
    cout <<"How many number? n";
    cin >>n;
    for (int i=0; i<n; i++){
        cout <<"Enter Number n";
        cin >> x;
        if(head==NULL){
            head = new node();
            head->data = x;
            head->next = NULL;
            tail = head;
        }else{
            node* newNode;
            newNode = new node();
            newNode->data=x;
            newNode->next = NULL;
            tail->next = newNode;
            tail = tail->next;
        }
    }
    cout << "Linked List :" << "n";
    node* trav = head;
    for (int i=0; i<n; i++){
        cout << (trav->data) << 'n';
        trav = trav->next;
    }
    int num;
    cout<<"what number do you want to insert in the list n";
    cin>>num;
    if(head==NULL){
        head = new node();
        head->data = num;
        head->next = NULL;
        tail = head;
    }else{
        node* newNode;
        newNode = new node();
        newNode->data=num;
        newNode->next = NULL;
        tail->next = newNode;
        tail = tail->next;
    }
    cout << "Linked List :" << "n";
    trav = head;
    while(trav != NULL){
        cout << (trav->data) << 'n';
        trav = trav->next;
    }
    return 0;
    }