Created
October 11, 2017 22:59
-
-
Save El-Sam/1d2078c28916e8e44a0dfc9064655f1c to your computer and use it in GitHub Desktop.
Reverse a linked list and return pointer to the head
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| 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