Leetcode question 21st-merge, Sorted Lists

Source: Internet
Author: User

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&AMP;&AMP;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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.