2016-04-22 75 views
-1

在此先感謝。雙鏈表核心轉儲

我正在做一個雙向鏈表。

一切工作正常,但我意識到,當我在中間的某個地方添加了一個新的類節點時,左指針仍然指向先前的節點(現在有兩個空格)。

所以我增加了一個新的節點指針上線46

然後在第51行,我告訴那個節點現在指向新節點。

所以:

  • 首先,我在太空中有了新節點臨時關閉

  • 然後我讓指針temp2遍歷列表

  • 最後我告訴temp3指向節點在temp2的節點

功能運行後,順序應該是temp2->temp->temp3

我主要:後我加線51,我的程序核心轉儲(分段錯誤),並關閉了。

我該如何解決這個問題?只有當我添加一些不在頭指針的位置時纔會發生。

void add(node *&head, node *&tail, node *&current) 
{ 
    node *temp = new node; //creates a pointer pointing to a new class node 
    cin >> temp->letter; // user input 

    current = head; // creates a pointer to point at the first node 
    while (current != NULL) // while list isn't empty 
    { 
     if (current->letter == temp->letter) 
     { // letter already exists 
      cout << "DUPLICATE: " << temp->letter << endl << endl; 
      return; 
     } 
     else 
     { // loop through list moving tail pointer to the end while checking for duplicates 
      tail = current; 
      current = current->right_link; 
     } 
    } 

    current = temp; // current = new added node 

    if (isEmpty(head)) 
    { // if first node 
     temp->left_link = NULL; 
     temp->right_link = NULL; 
     head = temp; // head and 
     tail = temp; // tail both point to first and only node. 
    } 
    else 
    { // if new letter value is less than head value 
     if(temp->letter < head->letter) 
     { 
      temp->right_link = head; // node points (right) to head 
      temp->left_link = NULL; // left most node point to nothing. 
      head->left_link = temp; // head (currently the second node) points (left) to first node 
      head = temp; // head pointer moves to the first position 
     } 
     else 
     { // if new node goes anywhere other than head 
      node *temp2 = head; // new node to cycle through list 
      while(temp2->right_link != NULL && temp2->right_link->letter < temp->letter) 
      { // if temp2 points to a node and that node's value is less than temp node value 
       temp2 = temp2->right_link; 
      } 
      node *temp3 = temp2->right_link; 
      temp->right_link = temp2->right_link; // when temp2 stops looping, temp will point to 
                // the same node as temp2. 
      temp2->right_link = temp; // temp2's current node will point to temp, causing temp 
           // to be added into the list (after temp2) 
      temp3->left_link = temp; // point the node (after the newly inserted node) left to new node 
      temp->left_link = temp2; // connects the left pointer between temp and temp2 
      if(temp->right_link == NULL) 
       tail = temp; 
     } 
    } 
    cout << "ADDED : " << temp->letter << endl << endl; 
} 
+0

你可以發佈[mcve]嗎?還有,你嘗試使用調試器嗎? – xvan

回答

0

如果temp2->right_link == NULL

46  node *temp3 = temp2->right_link; 

是一個NULL指針,所以你不能

51  temp3->left_link = temp; 

,如果你使用的調試器,它應該是很明顯。

+0

這完全應該是顯而易見的,感謝您的幫助。我會尋找所有人都在談論的調試器。 –