C++ 中的单链表读取的节点不超过 2 个

Singly Linked List in C++ is not reading more than 2 nodes

下面是一个用于在链表中插入的简单程序,但是,每当我 运行 程序时,它只读取列表的两个输入值并停止进一步执行。这是为什么?我无法捕捉到问题。

/**** Defining structure of node *****/
class Node{
    public:
        int data;
        Node* next;     
        Node(int val){
            data = val;
            next = NULL;
        }
};

/**** Inserting node at the end ****/
Node* insertAtEnd(Node* &head, int val){
    Node* n = new Node(val);
    if(head == NULL){
        head = n;
    }
    Node* tmp = head;
    while(tmp->next != NULL){
        tmp = tmp->next;
    }
    tmp->next = n;
    return tmp;
}

/**** Menu ****/
int menu(){
    int ch;
    cout<<"1. Insert node"<<endl;
    cout<<"Enter your choice: ";
    cin>>ch;
    cout<<endl;
    return(ch);
}

/**** Driver Code ****/
int main(){
    Node* head = NULL; int n, data;
    switch(menu()){
        case 1:
            cout<<"\nEnter number of nodes you want to enter: ";
            cin>>n;
            for(int i = 0; i<n; i++){
                cout<<"Enter data: ";
                cin>>data;
                insertAtEnd(head, data);
            }
            break;
        default:
            cout<<"Wrong Choice";
    }
}

insertAtEnd需要提前return与第一个节点,否则会运行进入无限循环。

  Node* insertAtEnd(int val) {
    Node* n = new Node(val);
    if (head == NULL) {
      head = n;
      return head;
    }
    Node* tmp = head;
    while (tmp->next != NULL) {
      tmp = tmp->next;
    }
    tmp->next = n;
    return tmp;
  }

您的代码大部分是 c 风格的,没有处理内存释放,因此内存泄漏。

我添加了 list class 以使其在 C++ 中更自然,添加使用析构函数来释放动态内存。

struct List {
  Node* head = nullptr;

  Node* insertAtEnd(int val) {
    Node* n = new Node(val);
    if (head == NULL) {
      head = n;
      return head;
    }
    Node* tmp = head;
    while (tmp->next != NULL) {
      tmp = tmp->next;
    }
    tmp->next = n;
    return tmp;
  }
  ~List() {
    while (head) {
      auto tmp = head->next;
      delete head;
      head = tmp;
    }
  }
};

Online demo

在列表末尾添加节点的函数中,我认为你应该按值传递指针“Node* head”不按引用传递“节点*&头”。 我实际上是这样编码的,我的代码运行正确,没有任何错误。你可以参考我下面的代码

Node* addtail(Node* head, int value) {   //  
    Node* p;
    Node* temp = new Node;
    temp->data = value;
    temp->next = NULL;
    if (head == NULL) {                  // if head empty => head = temp instantly 
        head = temp;
    }
    else {
        p = head;
        while (p->next != NULL) {         
            p = p->next;
        }
        p->next = temp;
    }
    return head;
}