Skip to content

Instantly share code, notes, and snippets.

@El-Sam
Created October 11, 2017 22:59
Show Gist options
  • Save El-Sam/1d2078c28916e8e44a0dfc9064655f1c to your computer and use it in GitHub Desktop.
Save El-Sam/1d2078c28916e8e44a0dfc9064655f1c to your computer and use it in GitHub Desktop.
Reverse a linked list and return pointer to the head
/*
Reverse a linked list and return pointer to the head
The input list will have at least one element
Node is defined as
class Node {
int data;
Node next;
}
*/
Node Reverse(Node head) {
if(head == null || head.next == null)
return head;
Node p = null;
Node tail= null;
while(head != null){
p = head.next;
head.next = tail;
tail = head;
head = p;
}
return tail;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment