Reverse a linked list


Given a linked list of N nodes. The task is to reverse this list.



Example 1:

Input:

LinkedList: 1->2->3->4->5->6

Output: 6 5 4 3 2 1

Explanation: After reversing the list, 

elements are 6->5->4->3->2->1.

Example 2:


Input:

LinkedList: 2->7->8->9->10

Output: 10 9 8 7 2

Explanation: After reversing the list,

elements are 10->9->8->7->2.

c++  implementation :

struct node *reverselist (struct node* head)

{

struct node* current = head;

struct node* next = NULL;

struct node* prev = NULL;

while (current != NULL )

{

next = current->next;             // marking next node

current->next = prev;             // reversing link

prev = current;                   // updating prev

current = next;                   // updating current

}

      return prev;

}
time complexity:0(n) 
darkmode