簡體   English   中英

在 C++ 的鏈表末尾插入一個節點

[英]Inserting a node at the end of Linked List in C++

我已經編寫了這段代碼來在單鏈表的末尾插入節點。 它編譯沒有錯誤,但在執行時沒有 output 顯示。 我哪里出錯了?

void insert_n(int x){
node* temp1 = new node();
temp1->data=x;
temp1->next=NULL;
node* temp2 = head;
while(temp2->next!=NULL){
    temp2 = temp2->next;
}
temp2->next=temp1;
}

void print(){
node* temp = head;
while(temp!=NULL){
    cout<<temp->data<<" ";
    temp = temp->next;
}
}

int main()
{
    head = NULL;
    insert_n(2);
    insert_n(3);
    insert_n(4);
    insert_n(5);
    print();
    return 0;
}

它是否因為列表為空時應該有特殊情況而失敗?

你是對的。 如果head == NULL那么你的插入 function 不能工作。 以下是您的insert_n() function的更正:

void insert_n(int x) {
  node* temp1 = new node();
  temp1->data = x;
  temp1->next = NULL;
  if (head == NULL) {
    head = temp1;
  } else {
    node* temp2 = head;
    while (temp2->next != NULL) {
      temp2 = temp2->next;
    }
    temp2->next = temp1;
  }
}

這是一個代碼示例: C 搜索和插入單鏈表的程序

您的head永遠不會設置為任何定義的值,因此它會失敗:

node* temp2 = head;
while(temp2->next!=NULL){

因為headNULL ,所以temp2也是NULL ,這會導致分段錯誤,當它嘗試訪問next時。

嘗試這個:

#include <iostream>

using namespace std; // this was missing !!!

struct node {
    int data;
    struct node* next;
};

struct node *head;

void insert_n(int x) {
    node* temp1 = new node();
    temp1->data = x;
    temp1->next = NULL;
    node* temp2 = head;
    while (temp2->next != NULL) {
        temp2 = temp2->next;
    }
    temp2->next = temp1;
}

void print() {
    node* temp = head;
    while (temp != NULL) {
        cout << temp->data << " ";
        temp = temp->next;
    }
}

int main()
{
    head = new node(); // without this you get a crash !!!
    insert_n(2);
    insert_n(3);
    insert_n(4);
    insert_n(5);
    print();
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM