Skip to content

Instantly share code, notes, and snippets.

@rishi93
Created December 18, 2017 10:23
Show Gist options
  • Select an option

  • Save rishi93/4eb8be6cbb971d6bed862fc3f398cab5 to your computer and use it in GitHub Desktop.

Select an option

Save rishi93/4eb8be6cbb971d6bed862fc3f398cab5 to your computer and use it in GitHub Desktop.
Linked List reversal
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