在链表的末尾添加节点

时间:2015-03-13 05:19:33

标签: c++ algorithm linked-list

我对我的程序添加一个新节点到链接它有点停滞不前,它应该被添加到列表的末尾但我尽我所能但仍然有一个解决方案,希望如果有人帮我的话 提前谢谢你;

这是代码

   #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;
    }

任何时候我运行它,得到一个点,然后停止工作,请帮助我,今天的任务到期,我不知道如何正确解决它

1 个答案:

答案 0 :(得分: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;
    }