C - 双重链接列表添加新节点会产生运行时错误

时间:2017-10-03 05:45:31

标签: c data-structures runtime-error doubly-linked-list

所以我有一个双链表的代码,这对于单链表很有效。当我尝试在节点的开头使用addFirst函数添加一个新节点时,当我有一行存在时,它会给我一个运行时错误(注释一行)。否则,该函数适用于单个链接列表,并且在没有该行的情况下不会出错。

void addFirst(DblList *lstPtr, int data)
{
  Node *newNodePtr = (Node *) malloc(sizeof (Node));
  if (newNodePtr == NULL) {
    printf("Unable to allocate new node\n");
    return;
  }
  newNodePtr->data = data;
  newNodePtr->next = NULL;
  newNodePtr->prev = NULL;
  if(lstPtr->nodeCount == 0){
    lstPtr->head = newNodePtr;
    lstPtr->tail = newNodePtr;
  }
  else{
    newNodePtr->next = lstPtr->head;
    lstPtr->head->prev = newNodePtr; //this is the toubling line
    lstPtr->head = newNodePtr;
  }
  lstPtr->nodeCount++;
}

以下是用户定义的类型 -

typedef struct Node {
  int data;
  struct Node *next;
  struct Node *prev;
} Node;

typedef struct DblList {
  struct Node *head;
  struct Node *tail;
  int nodeCount;
} DblList;

void initList(DblList *lstPtr)
{
  lstPtr->head = NULL;
  lstPtr->tail = NULL;
  int nodeCount = 0;
}

编辑 - 这似乎是一个分段错误,但我不确定。

0 个答案:

没有答案
相关问题