c++ - 在链接列表中的第 n 个位置插入显示段错误

标签 c++ linked-list

void Insert(int data, int n){
    Node* temp1 = new Node();
    temp1 -> data = data;
    temp1 -> next = NULL;
    if(n == 1){
        temp1 -> next = head;
        head = temp1;
        return;
    }
    else{
        Node* temp2 = head;
        for(int i; i< n-2; i++){
            temp2 = temp2 -> next;
        }
        temp1 -> next = temp2 -> next;
        temp2 -> next = temp1;
    }
}

我遇到了段错误,我无法找出问题所在。

最佳答案

void Insert(int data, int n)
{
   Node* add = new Node();   // Node to be added
   add -> data = data;
   add -> next = NULL;
   
   if(n == 1)
   {
     add -> next = head;
     head = temp1;
     return;
   }
   else
   {
     Node* temp2 = head;
     Node* prev = NULL;  //Previous pointer
     for(int i=0; i< n-2; i++)
      {
          if(i == n)   // n is required Node where we have to add it.
          {
             prev->next = add;
             add->next = temp;
             return;
          }
          else
          {
            prev = temp2;
            temp2 = temp2->next;
          }
      }
    
    }
}

关于c++ - 在链接列表中的第 n 个位置插入显示段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62608756/

相关文章:

c - 推送到仅包含 C 中唯一值的堆栈

c++ - 模拟加速大于最佳

c++ - 将列表分成相等的部分?

java - 链表addLast方法

java - 我该怎么做才能获取堆栈的元素并将它们添加到单个链表中?

c++ - 从链接列表中删除零个连续的求和节点-此代码如何用于这样的测试用例?

c++ - 如何在每个角上绘制一个带有自己纹理的三角形?

c++ - SPI 代码不稳定 - RPi 上的 Raspbian (Debian) Linux

c++ - 结构和类层次结构(制作模板)

c++ - C++中链表节点分配的段错误