Reverse a linked list hackerrank solution java
X Privacy & CookiesThis 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.
Constraints
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. Iterative approach: Initialize three pointers previous as NULL, current as head and next as NULL. 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: |