Showing posts with label reverse. Show all posts
Showing posts with label reverse. Show all posts

Wednesday, 12 August 2015

Reverse a doubly linked list

Problem Statement

You’re given the pointer to the head node of a doubly linked list. Reverse the order of the nodes in the list. The head node might be NULL to indicate that the list is empty.

Input Format You have to complete the Node* Reverse(Node* head) method which takes one argument - the head of the doubly linked list. You should NOT read any input from stdin/console.

Output Format Change the next and prev pointers of all the nodes so that the direction of the list is reversed. Then return the head node of the reversed list. Do NOT print anything to stdout/console.

Sample Input

NULL NULL <-- 2 <--> 4 <--> 6 --> NULL

Sample Output NULL NULL <-- 6 <--> 4 <--> 2 --> NULL

Explanation 1. Empty list, so nothing to do. 2. 2,4,6 become 6,4,2 o reversing in the given doubly linked list.


Reverse a linked list

Problem Statement

You’re given the pointer to the head node of a linked list. Change the next pointers of the nodes so that their order is reversed. The head pointer given may be null meaning that the initial list is empty.

Input Format You have to complete the Node* Reverse(Node* head) method which takes one argument - the head of the linked list. You should NOT read any input from stdin/console.

Output Format Change the next pointers of the nodes that their order is reversed and return the head of the reversed linked list. Do NOT print anything to stdout/console.

Sample Input

NULL 2 --> 3 --> NULL

Sample Output NULL 3 --> 2 --> NULL

Explanation 1. Empty list remains empty 2. List is reversed from 2,3 to 3,2


Print in Reverse

Problem Statement

You are given the pointer to the head node of a linked list and you need to print all its elements in reverse order from tail to head, one element per line. The head pointer may be null meaning that the list is empty - in that case, do not print anything!

Input Format You have to complete the void ReversePrint(Node* head) method which takes one argument - the head of the linked list. You should NOT read any input from stdin/console.

Output Format Print the elements of the linked list in reverse order to stdout/console (using printf or cout) , one per line.

Sample Input

1 --> 2 --> NULL 2 --> 1 --> 4 --> 5 --> NULL

Sample Output 2 1 5 4 1 2

Explanation 1. First list is printed from tail to head hence 2,1 2. Similarly second list is also printed from tail to head.