Created
December 18, 2017 10:23
-
-
Save rishi93/4eb8be6cbb971d6bed862fc3f398cab5 to your computer and use it in GitHub Desktop.
Linked List reversal
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
| class Node{ | |
| int data; | |
| Node next; | |
| Node(int data){ | |
| this.data = data; | |
| this.next = null; | |
| } | |
| } | |
| class LinkedList{ | |
| Node head; | |
| LinkedList(){ | |
| head = null; | |
| } | |
| void add(int key){ | |
| if(head == null){ | |
| head = new Node(key); | |
| return; | |
| } | |
| /* Traverse to the end of the list */ | |
| Node curr = head; | |
| while(curr.next != null){ | |
| curr = curr.next; | |
| } | |
| /* Insert element at the end of the list */ | |
| curr.next = new Node(key); | |
| } | |
| void printList(){ | |
| Node curr = head; | |
| while(curr != null){ | |
| System.out.print(curr.data + "->"); | |
| curr = curr.next; | |
| } | |
| System.out.print("null"); | |
| System.out.println(); | |
| } | |
| /* Function to reverse the linked list */ | |
| void reverse(){ | |
| Node prev = null; | |
| Node curr = head; | |
| Node next = null; | |
| while(curr != null){ | |
| next = curr.next; | |
| curr.next = prev; | |
| prev = curr; | |
| curr = next; | |
| } | |
| head = prev; | |
| } | |
| } | |
| public class Test{ | |
| public static void main(String[] args){ | |
| LinkedList list = new LinkedList(); | |
| list.add(1); | |
| list.add(2); | |
| list.add(3); | |
| list.printList(); | |
| list.reverse(); | |
| list.printList(); | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment