Problem Description :
Enter a list of two increments, merge the two linked lists, and make the nodes in the new list continue to be sorted in ascending order.
The implementation code is as follows:
#include <stdio.h> #include <stdlib.h> #include <stdbool.h> struct list{int date;
struct List *next;
};
struct list* domergelist (struct list *p1head,struct list *p2head) {if (p1head==null) return p2head;
else if (p2head==null) return p1head;
struct List *mergehead = NULL;
if (P1head->date <p2head->date) {mergehead = P1head;
Mergehead->next=domergelist (P1head->next,p2head);
}else {mergehead=p2head;
Mergehead->next=domergelist (P1head,p2head->next);
} return mergehead;
} int main () {struct list *p1head= (struct list *) malloc (sizeof (struct list));
struct list *p2head= (struct list *) malloc (sizeof (struct list)); p1head->date=0;
p1head->next=null;
p2head->date=1;
p2head->next=null;
int i;
struct List *p1temp=p1head,*p2temp=p2head;
for (i=1;i<4;i++) {p1temp->next= (struct list *) malloc (sizeof (struct list));
p1temp->next->date=i;
p1temp->next->next=null; p2temp->next= (struct List *) malloc (sizeof (struct List));
p2temp->next->date=i*3;
p2temp->next->next=null;
p1temp=p1temp->next;
p2temp=p2temp->next;
} P1temp=p1head,p2temp=p2head;
printf ("This is first list:\t");
while (P1temp!=null) {printf ("%d\t", p1temp->date);
p1temp=p1temp->next;
} printf ("\nthis is second list:\t");
while (P2temp!=null) {printf ("%d\t", p2temp->date);
p2temp=p2temp->next;
} printf ("\nthis is merge List:\t");
struct List *head = domergelist (P1head,p2head);
while (Head!=null) {printf ("%d\t", head->date);
head=head->next;
} printf ("\ndomerge done!\n");
return 0; }
References:
Sword means offer
Notes:
Reprint Please specify source: http://blog.csdn.net/wsyw126/article/details/51372134
Author: WSYW126