双链表核心转储
问题描述:
在此先感谢。双链表核心转储
我正在做一个双向链表。
一切工作正常,但我意识到,当我在中间的某个地方添加了一个新的类节点时,左指针仍然指向先前的节点(现在有两个空格)。
所以我增加了一个新的节点指针上线46
然后在第51行,我告诉那个节点现在指向新节点。
所以:
首先,我在太空中有了新节点临时关闭
然后我让指针
temp2
遍历列表最后我告诉
temp3
指向节点在temp2
的节点
功能运行后,顺序应该是temp2->temp->temp3
我主要:后我加线51,我的程序核心转储(分段错误),并关闭了。
我该如何解决这个问题?只有当我添加一些不在头指针的位置时才会发生。
void add(node *&head, node *&tail, node *¤t)
{
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;
}
答
如果temp2->right_link == NULL
46 node *temp3 = temp2->right_link;
是一个NULL指针,所以你不能
51 temp3->left_link = temp;
,如果你使用的调试器,它应该是很明显。
+0
这完全应该是显而易见的,感谢您的帮助。我会寻找所有人都在谈论的调试器。 –
你可以发布[mcve]吗?还有,你尝试使用调试器吗? – xvan