我正在尝试合并两个排序的链表,但没有获得所需的O/P。我认为地址分配有一些问题,但我不确定。有没有人能告诉我为什么我得不到任何o?
struct Node* SortedMerge(struct Node* a, struct Node* b)
{
struct Node *head;
struct Node **tail=&head;
while(1)
{
if(a==NULL)
{
*tail=b;
break;
}
if(b==NULL)
{
*tail=a;
break;
}
if(a->data<=b->data)
{
*tail=a;
a=a->next;
(*tail)->next=NULL;
}
else
{
*tail=b;
b=b->next;
(*tail)->next=NULL;
}
(*tail)=(*tail)->next;
}
return head;
}发布于 2018-05-20 21:26:59
(*tail)=(*tail)->next;将其替换为:-
tail = &( (*tail)->next );我希望它能起作用。
发布于 2018-05-20 21:41:13
您应该考虑使用append函数来简化代码。下面是一个示例:
#include <stdio.h>
#include <stdlib.h>
struct List {
struct Node *head;
struct Node *tail;
};
struct Node {
int data;
struct Node *next;
};
void append(struct List *list, struct Node *node) {
struct Node *nodeCopy = malloc(sizeof(struct Node));
nodeCopy->data = node->data;
nodeCopy->next = NULL;
if (list->head == NULL) { // Empty list
list->head = nodeCopy;
list->tail = nodeCopy;
} else {
list->tail->next = nodeCopy;
list->tail = nodeCopy;
}
}
void print(struct List *list) {
for (struct Node *node = list->head; node != NULL; node = node->next) {
printf("%d,", node->data);
}
printf("\n");
}
struct List* SortedMerge(struct Node* a, struct Node* b)
{
struct List *list = malloc(sizeof(struct List));
list->head = NULL;
list->tail = NULL;
while(1)
{
if(a==NULL && b==NULL)
{
break;
}
if(a==NULL && b!=NULL)
{
append(list, b);
b = b->next;
}
else if(b==NULL && a!=NULL)
{
append(list, a);
a = a->next;
}
else if(a->data<=b->data)
{
append(list, a);
a = a->next;
}
else
{
append(list, b);
b = b->next;
}
}
return list;
}
int main() {
struct List listA = { NULL, NULL };
struct List listB = { NULL, NULL };
struct Node node1 = { 1, NULL };
struct Node node2 = { 2, NULL };
struct Node node3 = { 3, NULL };
struct Node node4 = { 4, NULL };
struct Node node5 = { 5, NULL };
append(&listA, &node1);
append(&listA, &node4);
print(&listA);
append(&listB, &node2);
append(&listB, &node3);
append(&listB, &node5);
print(&listB);
struct List *mergedList1 = SortedMerge(listA.head, listB.head);
print(mergedList1);
struct List *mergedList2 = SortedMerge(listB.head, listA.head);
print(mergedList2);
return 0;
}https://stackoverflow.com/questions/50434958
复制相似问题