Showing posts with label head. Show all posts
Showing posts with label head. Show all posts

Wednesday, 12 August 2015

Merge two sorted linked lists

Problem Statement

You’re given the pointer to the head nodes of two sorted linked lists. The data in both lists will be sorted in ascending order. Change the next pointers to obtain a single, merged linked list which also has data in ascending order. Either head pointer given may be null meaning that the corresponding list is empty.

Input Format You have to complete the Node* MergeLists(Node* headA, Node* headB) method which takes two arguments - the heads of the two sorted linked lists to merge. You should NOT read any input from stdin/console.

Output Format Change the next pointer of individual nodes so that nodes from both lists are merged into a single list. Then return the head of this merged list. Do NOT print anything to stdout/console.

Sample Input 1 -> 3 -> 5 -> 6 -> NULL 2 -> 4 -> 7 -> NULL

15 -> NULL 12 -> NULL

NULL 1 -> 2 -> NULL

Sample Output 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> 7 12 -> 15 -> NULL 1 -> 2 -> NULL

Explanation 1. We merge elements in both list in sorted order and output.


Insert at head of linkedlist

Problem Statement

You’re given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer, insert this node at the head of the linked list and return the new head node. The head pointer given may be null meaning that the initial list is empty.

Input Format You have to complete the Node* Insert(Node* head, int data) method which takes two arguments - the head of the linked list and the integer to insert. You should NOT read any input from stdin/console.

Output Format Insert the new node at the head and return the head of the updated linked list. Do NOT print anything to stdout/console.

Sample Input

NULL , data = 1 1 --> NULL , data = 2

Sample Output 1 --> NULL 2 --> 1 --> NULL

Explanation 1. We have an empty list, on inserting 1, 1 becomes new head. 2. We have a list with 1 as head, on inserting 2, 2 becomes the new head.