Reverse a linked list hackerrank solution java

X

Privacy & Cookies

This site uses cookies. By continuing, you agree to their use. Learn more, including how to control cookies.

Got It!
Advertisements

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 thevoidreversePrint(SinglyLinkedListNode head)method which takes one argument the head of the linked list. You should NOT read any input from stdin/console.

The first line of input containst, the number of test cases.
The input of each test case is as follows:

  • The first line contains an integer n, denoting the number of elements in the list.
  • The next n lines contain one element each, denoting the elements of the linked list in the order.

Constraints

  • 1 <= n <= 1000
  • 1<= listi<= 1000 ,wherelist iis theithelement in the list.

Output Format

Complete the reversePrint function in the editor below and print the elements of the linked list in the reverse order, each in a new line.

Sample Input

3 5 16 12 4 2 5 3 7 3 9 5 5 1 18 3 13

Sample Output

5 2 4 12 16 9 3 7 13 3 18 1 5

Explanation

There are three test cases.
The first linked list has5elements:16 -> 12 -> 4 -> 2 -> 5. Printing this in reverse order will produce:5 -> 2 -> 4 -> 12 -> 16.
The second linked list has3elements:7 -> 3 -> 9. Printing this in reverse order will produce:9 -> 3 -> 7.
The third linked list has5elements:5 -> 1 -> 18 -> 3 -> 13. Printing this in reverse order will produce:13 -> 3 -> 18 -> 1 -> 5.

Iterative approach:

Initialize three pointers previous as NULL, current as head and next as NULL.
Iterate through the linked list. In loop, do following.
// Before changing next of current,
// store next node
next = current->next
// Now change next of current
// This is where actual reversing happens
current->next = previous

// Move prev and curr one step forward
previous = current
current = next

Code:

static void reversePrint(SinglyLinkedListNode head) { SinglyLinkedListNode previous = null; SinglyLinkedListNode next = null; SinglyLinkedListNode current = head; while(current != null) { next = current.next; current.next = previous; previous = current; previous = next; } while(previous != null) { System.out.println(previous.data); previous = previous.next; }

Hope you guys understand the simple solution of reverse a linked list in java.

In next blog we will see other operations on linked list till then Bye Bye..!

Thanks for reading!

Happy Coding..!

Thank You!

Advertisements

Share this: