【发布时间】:2014-10-14 02:27:59
【问题描述】:
我知道这个问题已经被问过多次,并部分回答了合并排序问题,但我似乎无法正确回答。
这是我的代码:
#include <iostream>
using namespace std;
struct listNode {
int info;
struct listNode *next;
};
struct listNode * addHead(struct listNode* head, int k);
void printAll(struct listNode *head);
struct listNode * deleteLast(struct listNode *head);
struct listNode * append(struct listNode *a, struct listNode *b);
struct listNode * zip(struct listNode *a, struct listNode *b);
struct listNode * merge(struct listNode *a, struct listNode*b);
int main()
{
listNode *list1 = 0;
listNode *list2 = 0;
listNode *list3 = 0;
listNode *list4 = 0;
listNode *list5 = 0;
//fill list1
list1 = addHead(list1, 6);
list1 = addHead(list1, 4);
list1 = addHead(list1, 2);
//fill list2
list2 = addHead(list2, 3);
list2 = addHead(list2, 1);
//test deleteLast
cout << "List 1 contains: " << endl;
printAll(list1);
cout << "Deleting last node of List 1. Now contains: " << endl;
list1 = deleteLast(list1);
printAll(list1);
cout << "List 2 contains: " << endl;
printAll(list2);
//test append
cout << "Appending list 1 and list 2 yields: " << endl;
list3 = append(list1, list2);
printAll(list3);
//zip test
cout << "The zipped list of list 1 and list 2 is: " << endl;
list4 = zip(list1, list2);
printAll(list4);
//merge test
cout << "The merged list of list1 and list 2 is: " << endl;
list5 = merge(list1, list2);
printAll(list5);
return 0;
}
struct listNode *deleteLast(struct listNode *head) {
if (head == 0) {
return NULL;
} else if (head->next == 0) {
delete head;
return NULL;
} else {
head->next = deleteLast(head->next);
}
return head;
}
struct listNode * addHead(struct listNode *head, int k) {
listNode *nnode = new listNode;
nnode->info = k;
nnode->next = head;
return nnode;
}
void printAll(listNode *head) {
if (head == 0) {
cout << endl;
} else {
cout << head->info << "->";
printAll(head->next);
}
}
struct listNode * append(struct listNode *ahead,struct listNode *bhead) {
if (bhead == 0) {
return ahead;
} else if (ahead == 0) {
return bhead;
} else {
ahead->next = append(ahead->next, bhead);
}
return ahead;
}
struct listNode * zip(struct listNode *a, struct listNode *b)
{
if (b == 0) {
return 0;
} else {
listNode *tmp = a->next;
a->next = b;
a->next = zip(b, tmp);
}
return a;
}
struct listNode *merge(struct listNode *a, struct listNode *b)
{
listNode *result = NULL;
if (a == NULL)
return b;
else if (b == NULL)
return a;
if (a->info < b->info) {
result = a;
result->next = merge(a->next, b);
} else {
result = b;
result -> next = merge(a, b->next);
}
return result;
}
现在它只是不能正常工作。我陷入无限循环,然后发生分段错误。谁能告诉我我有什么问题?
【问题讨论】:
-
这可能是学习使用调试器的好机会。
-
请参阅stackoverflow.com/help/on-topic:寻求调试帮助的问题(“为什么这段代码不起作用?”)必须包括所需的行为、特定问题或错误以及重现它所需的最短代码问题本身。没有明确问题陈述的问题对其他读者没有用处。请参阅:如何创建最小、完整和可验证的示例。