Combine Two ordered linked lists into one ordered linked list

Source: Internet
Author: User

Problem definition:

Write a function sortedmerge. This function has two parameters, both of which are an incremental linked list. The function is to combine these two incremental linked lists into an incremental linked list, the returned value of sortedmerge is the new linked list. The new linked list is composed of the first two linked lists in ascending order of elements, that is, it does not create new elements.

For example, there are two linked lists:

List1: 5-> 10-> 15

List2: 2-> 3-> 20

The sortedmerge function returns a pointer to the new linked list. The new linked list should be like this: 2-> 3-> 5-> 10-> 15-> 20

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

Method 1 (virtual node)

This method uses a virtual node (dummy node) as the Start Node of the result linked list. To facilitate the insertion of nodes at the end of the linked list, you also need to use a tail pointer to point to the End Node of the linked list.

Initially, when the result linked list is empty, the tail Pointer Points to a virtual node. Because a virtual node is a temporary variable allocated on the stack, its operations are very efficient. In loop iteration, each time a node from A or B is taken and inserted to the end of the result linked list, the next field of the virtual node is the address of the result linked list at the end of the loop, that is, the expected return value.

#include <stdio.h>#include <stdlib.h>#include <assert.h>/*Link list node*/struct node{int data;struct node* next;};/*Function to insert a node at the begining of the linked list*/void push(struct node** head_ref, int new_data){/* allocate node*/struct node* new_node = (struct node*)malloc(sizeof(struct node));/* put in the data*/new_node->data = new_data;/*link the old list off the new node*/new_node->next = (*head_ref);/*move the head to point to the new node*/(*head_ref) = new_node;}/* Function to print nodes in a given linked list */void printList(struct node* node){while(node != NULL){printf("%d ", node->data);node = node->next;}printf("\n");}/*pull off the front node of the source and put it in dest*//* MoveNode() function takes the node from the front of the source, and move it to the front of the dest.It is an error to call this with the source list empty.Before calling MoveNode():source == {1, 2, 3}dest == {1, 2, 3}After calling MoveNode():source == {2, 3}dest == {1, 1, 2, 3}*/void MoveNode(struct node** destRef, struct node** sourceRef){/* the front source node */struct node* newNode = *sourceRef;assert(newNode != NULL);/*Advance the source pointer */*sourceRef = newNode->next;/* Link th eold dest off the new node */newNode->next = *destRef;/*Move dest to point to the new node */*destRef = newNode;}/*Takes two lists sorted in creasing order, and splices their nodes together to make ont big sorted list which is returned. */struct node* SortedMerge(struct node* a, struct node* b){/* a dummy first node to hang the result on */struct node dummy;/* tail points to the last result node */struct node* tail = &dummy;/*so tail->next is the places to add new nodes to the result*/dummy.next = NULL;while(1){if(a == NULL){tail->next = b;break;}else if(b == NULL){tail->next = a;break;}if(a->data <= b->data){MoveNode(&(tail->next), &a);}else{MoveNode(&(tail->next), &b);}tail = tail->next;}return (dummy.next);}/*Drier program to test above functions */int main(int argc, char* argv[]){/*start with the empty list */struct node* res = NULL;struct node* a = NULL;struct node* b = NULL;/*Let us create two sorted linked lists to test the functions Created lists shall be a:5->10->15, b:2->3->20 */push(&a, 15);push(&a, 10);push(&a, 5);push(&b, 20);push(&b, 3);push(&b, 2);res = SortedMerge(a, b);printf("\nMerged Linked List is:\n");printList(res);return 0;}


Method 2 (local reference)

This method is very similar to the previous method. Instead of using a virtual node (dummy node), This method uses a pointer to the pointer, struct node ** lastptrref, which points to the last node of the result linked list. In this method, all the work completed by the virtual node is completed by lastptrref.

/* method2 Using local References */struct node* SortedMerge(struct node* a, struct node* b){struct node* result = NULL;/*point to the last result pointer */struct node** lastPtrRef = &result;while(1){if(a == NULL){*lastPtrRef = b;break;}else if(b == NULL){*lastPtrRef = a;break;}if(a->data <= b->data){MoveNode(lastPtrRef, &a);}else{MoveNode(lastPtrRef, &b);}/*tricky:advance to point to the next ".next" field */lastPtrRef = &((*lastPtrRef)->next);}return (result);}

Method 3 (recursion)

Merge operations are a type of operation that can be completed by recursion. Recursive Implementation is clearer and easier to understand than iterative implementation. Even so, you may not want to use recursion to implement this operation, because the stack space used by the recursive method is proportional to the length of the linked list.

/*Using Recursion*/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);}

Http://www.geeksforgeeks.org/archives/3622

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.