我正在尝试实现一种算法来合并C ++中的两个链接列表,以便在hackerrank上解决相应的problem 。但是我收到了分段错误错误消息,我不知道为什么。这是我的代码:
Node* MergeLists(Node *headA, Node* headB)
{
if (headA == NULL || headB == NULL) {
return (headA == NULL ? headB : headA);
}
Node* currentA = headA; currentA->next = NULL;
Node* nextA = headA->next; nextA->next = NULL;
Node* currentB = headB; currentB->next = NULL;
Node* nextB = currentB->next; nextB->next = NULL;
while (currentA != NULL && currentB != NULL) {
while (currentB != NULL && nextA != NULL && nextA->data <= currentB->data) {
currentA = nextA;
nextA = nextA->next;
}
if (currentA != NULL && currentA->data <= currentB->data) {
currentA->next = currentB;
currentA = nextA;
if (nextA != NULL) {
nextA = nextA->next;
}
}
while (currentA != NULL && nextB != NULL && nextB->data <= currentA->data){
currentB = nextB;
nextB = nextB->next;
}
if (currentB != NULL && currentB->data <= currentA->data) {
currentB->next = currentA;
currentB = nextB;
if (nextB != NULL) {
nextB = nextB->next;
}
}
}
if (headA->data <= headB->data) {
return headA;
} else {
return headB;
}
}
错误消息如下:
GDB trace:
Reading symbols from solution...done.
[New LWP 2775]
Core was generated by `solution'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0 0x0000000000400c94 in MergeLists (headA=headA@entry=0x1c46c30,
headB=headB@entry=0x1c46cb0) at solution.cc:32
32 ca -> next = cb;
#0 0x0000000000400c94 in MergeLists (headA=headA@entry=0x1c46c30,
headB=headB@entry=0x1c46cb0) at solution.cc:32
#1 0x0000000000400a0b in MergeLists (headB=0x1c46cb0, headA=0x1c46c30)
at solution.cc:103
#2 main () at solution.cc:100
答案 0 :(得分:0)
我认为你必须让你的指针“新”然后使用它们。 当使用new运算符时,在堆上而不是在堆栈上声明对象。因此,您可以在函数中使用它们。 我想你需要这样的东西:
Node* currentA = new Node();currentA = headA; currentA->next = NULL;
Node* nextA = new Node(); nextA = headA->next; nextA->next = NULL;
Node* currentB = new Node(); currentB = headB; currentB->next = NULL;
Node* nextB = new Node(); nextB = currentB->next; nextB->next = NULL;
我希望它会对你有所帮助。 抱歉我的英文!
答案 1 :(得分:0)
我猜分段错误是由解除引用的NULL指针引起的。
下一个指针的NULL初始化导致它。所有这些&#39; - &gt; next = NULL&#39;语句可以从下面的代码段中删除。它应该适用于合并2个链接列表,因为其余代码看起来没问题。
Node* currentA = headA; currentA->next = NULL;
Node* nextA = headA->next; nextA->next = NULL;
Node* currentB = headB; currentB->next = NULL;
Node* nextB = currentB->next; nextB->next = NULL;
希望它有所帮助!