This topic is meant to synthesize an ordered list of two ordered lists, and to investigate the merging algorithm and the operation of the linked list.
The code is relatively simple, simply say the function of the three pointers in the merge function, sum is the first pointer to return, CUR is the link to return to the location, put is to take the L1 or L2 in a certain pointer node. The full operating code is as follows:
#include <stdio.h> #include <string.h> #include <stdlib.h>struct listnode{int value; ListNode *next;}; ListNode *mergetwolist (ListNode *l1,listnode *l2) {ListNode *sum; ListNode *cur; ListNode *put;sum=null;//will be Returnedif ((l1==null) | | (L2==null)) Return L1?l1:l2;while (L1&&L2) {if (l1->value<l2->value) {put=l1;l1=l1->next;} Else{put=l2;l2=l2->next;} if (sum==null) {sum=put;cur=sum;} Else{cur->next=put;cur=cur->next;}} if (L1) cur->next=l1;if (L2) Cur->next=l2;return sum;} int main () {int n,m;printf ("Please input the first list number:") and while (scanf ("%d", &m)!=eof) {ListNode *h1= (listnode *) malloc (sizeof (ListNode)); ListNode *p1=h1;p1->next=null;printf ("Please input the first list:\n"); int tmp,i;scanf ("%d", &tmp);p 1-> Value=tmp;for (i=0;i<m-1;i++) {scanf ("%d", &tmp); ListNode *q1= (listnode*) malloc (sizeof (ListNode)); q1->value=tmp;p1->next=q1;p1=q1;p1->next=null;} printf ("Please input the second list number:"); scanf ("%d", &n);p rintf ("PlEase input the second list:\n "); ListNode *h2= (listnode*) malloc (sizeof (ListNode)); ListNode *p2=h2;p2->next=null;scanf ("%d", &tmp);p 2->value=tmp;for (i=0;i<n-1;i++) {scanf ("%d",& TMP); ListNode *q2= (listnode*) malloc (sizeof (ListNode)); q2->value=tmp;p2->next=q2;p2=q2;p2->next=null;} printf ("After Merge:"); ListNode *list=mergetwolist (H1,H2); ListNode *p=list;while (P) {printf ("%d", p->value);p =p->next;} Free (H1), free (H2);p rintf ("\ n");p rintf ("Please input the first list number:");} return 0;}
Leetcode question 21st-merge, Sorted Lists