【问题标题】:Assigning pointer to a link list node throws "Segmentation Fault"将指针分配给链接列表节点会引发“分段错误”
【发布时间】:2017-01-24 12:37:36
【问题描述】:

我正在尝试用 C++ 中的链接列表实现插入排序。但是,每当我试图将指向新节点的指针分配给链接时,它都会给出“分段错误(核心转储)”。我检查了“(*head)->next = newNode;”这行给出了这个错误。

要运行程序,请编译程序并作为输入复制insertionSort 开始之前的两行注释。

#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;

class Node
{
public:
  int num;
  Node *prev;
  Node *next;
  Node(int input);
};

Node::Node(int input)
{
  num = input;
  prev = NULL;
  next = NULL;
}
/*
5 2  
1 5 3 4 2
*/
void insertionSort(Node **head, int newInput)
{
  Node* newNode = new Node(newInput);
  if (*head == NULL)
  {
    *head = newNode;
  }
  else
  {
    Node *itr = *head;
    if (itr->num >= newInput)
    {
      newNode->next = itr->next;
      itr->prev = newNode;
      *head = itr;
    }
    else
    {
      Node *itr = (*head)->next;
      while (itr != NULL)
      {
        if (itr->num >= newInput)
        {
          newNode->prev = itr->prev;
          newNode->next = itr;
          itr->prev = newNode;
          newNode->prev->next = newNode;
          newNode = NULL;
        }
        itr = itr->next;
      }
      if (newNode != NULL)
      {
        if (itr == NULL) {
          (*head)->next = newNode;
        }
        else
          itr->next = newNode;
      }
    }
  }
}

void printList(Node *head)
{
  Node *itr = head;
  while (itr != NULL)
  {
    cout << itr->num << " ";
    itr = itr->next;
  }
  cout << endl;
}

int main()
{
  /* Enter your code here. Read input from STDIN. Print output to STDOUT */

  int n, k;
  cin >> n >> k;

  Node *head = NULL;
  int num, i = -1;
  while (++i < n)
  {
    cin >> num;
    insertionSort(&head, num);
  }

  printList(head);

  return 0;
}

【问题讨论】:

  • 您是否尝试使用调试器单步执行代码,同时观察变量的值?
  • 请删除输入并使用可重现问题的硬编码值。不要依赖别人来猜测你在事情发生时做了什么。

标签: c++ linked-list segmentation-fault


【解决方案1】:

尝试改变

itr->prev = newNode;

新节点->上一个=新节点;

【讨论】:

    【解决方案2】:

    我正在运行您的代码,但遇到写访问冲突。 "newNode->prev 为 nullptr"

    您似乎在第 53 行混淆了变量:

    newNode->prev->next = newNode;
    

    应该是:

    its->prev->next = newNode;
    

    它必须在其->prev 被覆盖之前执行。但是代码仍然无法按您想要的方式运行。你已经付出了更多的努力。在 while 循环中,将 newNode 设置为 NULL,然后重复。

    你真的应该评论你的代码。当您描述自己在做什么时,您会更好地了解自己的错误。

    顺便说一句,您是否注意到您在第 45 行从第 36 行屏蔽了 Node* itr?您可以重用现有对象,因为您不再使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-25
      • 2016-01-02
      • 1970-01-01
      相关资源
      最近更新 更多