typedef struct Nodetag{TYPE val; struct Nodetag * next;} Node;
typedef Node* pNode;
Node* combine(Node* p1, Node* p2)
{
Node *head, *p;
if(p1 == NULL) return p2;
if(p2 == NULL) return p1;
head = (p1->val < p2->val)?p1:p2;
while(p1!=NULL && p2!=NULL){
if(p1->val > p2->val){p = p1; p1 = p2; p2 = p;}
while(p1!=NULL && p2!=NULL && p1->val<p2->val)
{
p = p1;
p1 = p1->next;
}
p->next = p2;
}
return head;
}
Node* build(int A[], int n)
{
Node * head, *p;
int i;
head = p = (Node*)malloc(sizeof(Node));
p->val = A[0];;
for(i = 1; i < n; ++i)
{
p->next = (Node*)malloc(sizeof(Node));
p = p->next;
p->val = A[i];
}
p->next = NULL;
return head;
}
void printl(Node* head)
{
while(head != NULL)
{
printf("%d ", head->val);
head = head->next;
}
printf("\n");
}
Node* merge(Node* p1, Node* p2)
{
if(p1 == NULL) return p2;
if(p2 == NULL) return p1;
pNode head = NULL, k = NULL;
bool isHead ;
while(p1!=NULL && p2!=NULL)
{
isHead = false;
if(p1->val < p2->val){
if(head == NULL) {head = k = p1; isHead=true;}
else{
k->next = p1;
}
p1 = p1->next;
}else{
if(head == NULL) {head = k = p2;isHead = true;}
else{
k->next = p2;
}
p2 = p2->next;
}
if(!isHead) k = k->next;
}
if(p1!=NULL) k->next = p1;
if(p2!=NULL) k->next = p2;
return head;
}
int main()
{
pNode p1, p2, p3, p4, head1, head2;
int A[] = {3,26,41,52},
B[] = {9,38,49,57};
p1 = build(A, 4);
p2 = build(B, 4);
p3 = build(A, 4);
p4 = build(B, 4);
printl(p1);
printl(p2);
head1 = combine(p1, p2);
head2 = merge(p3, p4);
printl(head1);
printl(head2);
}
合并两个排好序的链表
最新推荐文章于 2022-11-07 14:27:38 发布