Merging two ordered linked lists into an ordered list

Source: Internet
Author: User

Problem definition:

Write a function Sortedmerge function, the function has two parameters, are incrementing the list, function is to merge the two increments of the linked list for an incremented list, sortedmerge The return value is a new linked list. The new list is composed of the first two linked lists in ascending order of elements, meaning that it does not create new elements.

For example: Here are two linked lists, each of which is

List1:5->10->15

List2:2->3->20

The Sortedmerge function returns a pointer to the new linked list, which should look like this: 2->3->5->10->15->20

The program needs to consider the following: two linked lists (function parameters) may be empty, or one of the list has been traversed, the other linked list has many elements.

struct node* sortedmerge (struct node* A, struct node* b)  {      struct node* result = NULL;            /*base cases*/      if (a = = NULL)          return (b);      else if (b = = NULL)          return (a);        /*pick either A or B, and recur *      /if (a->data <= b->data)      {          result = A;          Result->next = Sortedmerge (A->next, b);      }      else      {          result = B;          Result->next = Sortedmerge (A, b->next);      }      return (result);  }  
The single-linked list A and B, which are incrementally ordered for two elements, combine A and b into a single-linked list C that is descending order by element (allows the addition of new nodes)

void Merge (Lnode *a,lnode *b,lnode **c) {lnode *p,*q,*s;p=a->next;q=b->next; (*c) =a; (*c)->next=null;free (B); while (P!=null&&q!=null) {if (p->data<q->data) {s=p;p=p->next;} Else{s=q;q=q->next;} Cha rus->next= (*c)->next; (*c)->next=s;} if (p==null) p=q;while (p!=null) {                s=p;p=p->next;s->next= (*c)->next; (*c)->next=s;}}



Merging two ordered linked lists into an ordered list

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.