【问题标题】:Inserting a node at the end of Linked List in C++在 C++ 中的链表末尾插入一个节点
【发布时间】:2020-06-16 07:00:02
【问题描述】:

我已经编写了这段代码来在单链表的末尾插入节点。它编译没有错误,但在执行时没有输出显示。我哪里出错了?

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 是什么,在insert_n 中对它的写入访问为零。因此,无论该函数做什么,它都无法更改 print 访问的内容。在相关说明中,如果 temp2 最初是空指针,则 temp2-&gt;next 无效。您应该在那里遇到分段错误。

标签: c++ data-structures linked-list


【解决方案1】:

是的,你是对的。如果head == NULL 则您的插入功能无法工作。 以下是您的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 Program to Search and insert in a singly Linked List

【讨论】:

    【解决方案2】:

    您的 head 从未设置为任何定义的值,因此它在以下位置失败:

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

    因为headNULL,所以temp2 也是NULL,当它尝试访问next 时会导致分段错误。

    【讨论】:

      【解决方案3】:

      试试这个:

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

      【讨论】:

      猜你喜欢
      • 2020-11-15
      • 2015-02-08
      • 2011-08-13
      • 2015-12-14
      • 1970-01-01
      • 2016-10-11
      相关资源
      最近更新 更多