Print linked list in reverse hackerrank

We have to print a Linked List in Reverse order. For example:

5 // number of elements of Linked List  1 2 3 4 5

The linked List will be:

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

We have to Print Like

Output 5 4 3 2 1

Here, I have represented the logic of the Print in Reverse using Recursion. Please Dry and Run the code for the better Understanding.

void reversePrint[SinglyLinkedListNode* head] { if[head==NULL] {return ; } else { reversePrint[head->next]; cout 12 -> 16.
The second linked list has 3 elements: 7 -> 3 -> 9. Printing this in reverse order will produce: 9 -> 3 -> 7.
The third linked list has elements: 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…!



Print in Reverse



Given a pointer to the head of a singly-linked list, print each data value from the reversed list. If the given list is empty, do not print anything. Example head* refers to the linked list with data values 1->2->3->Null Print the following: 3 2 1 Function Description: Complete the reversePrint function in the editor below. reversePrint has the following parameters: SinglyLinkedListNode pointer head: a reference to the head of the list Prints The data values of each node in the reversed list. Input Format: The first line of input contains t, the number of test cases. The input of each test case is as follows: 1. The first line contains an integer n, the number of elements in the list. 2. Each of the next n lines contains a data element for a list node. Constraints: 1. 1next; } } In C++: //the following fuction is all that is needed to complete the //challenge in hackerrank platform. void ReversePrint[Node *head] { // This is a "method-only" submission. // You only need to complete this method. if[head!=NULL] { ReversePrint[head->next]; cout

Chủ Đề