I just struggled through a simple interview question: Please reverse a singly linked list.
While I failed to provide a working answer in time to save the interview,
Reversing the SinglyLinkedList: Input: 1->2->3->4->5->NULL Output: 5->4->3->2->1->NULL
To understand The Solution we have to keep track of previous head and next variables for example in above input Head = 1 ; next = 2 we don't have previous so assume previous = null loop the list till head is not null. reverse the connections(previous and next) of head. Below is the code
var reverseList = function(head) {
let previous = null;
while(head !== null){
let next = head.next;
head.next = previous;
previous= head
head = next;
}
return previous;
};