# Reverse a linked list HackerRank Solution

Reverse a linked list HackerRank Solution

In this Reverse a linked list HackerRank solution, 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.

Example
references the list

Manipulate the  pointers of each node in place and return , now referencing the head of the list .

Function Description

Complete the reverse function in the editor below.

reverse has the following parameter:

Returns

• SinglyLinkedListNode pointer: a reference to the head of the reversed list

Input Format

The first line contains an integer , the number of test cases.

Each test case has the following format:

The first line contains an integer , the number of elements in the linked list.
Each of the next  lines contains an integer, the  values of the elements in the linked list.

Constraints

• , where  is the  element in the list.

Sample Input

1
5
1
2
3
4
5


Sample Output

5 4 3 2 1


Explanation

The initial linked list is: .

The reversed linked list is: .

## Reverse a linked list HackerRank solution

I will Provide solution in Multiple programming languages for you. If you are not able to find the code in required language then please share in comments so that our team can help you.

### Problem Solution in Python

def reverse(llist):
prev = None
while llist != None:
# get next
nxt = llist.next
# point current to prev
llist.next = prev
# update prev before next iteration
prev = llist
# update head to be nxt and restart
llist = nxt

return prev

### Problem Solution in Java

public static SinglyLinkedListNode reverse(SinglyLinkedListNode llist) {
if (llist == null) {
return null;
}

//single node
if (llist.next == null) {
return llist;
}

while (currNode != null) {
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}

llist = prevNode;
return llist;
}

### Problem Solution in JavaScript

const reverse = head => {
let prev = null

}

return prev
}

### Problem Solution in C++

SinglyLinkedListNode* reverse(SinglyLinkedListNode* llist) {
}