Skip to content

Instantly share code, notes, and snippets.

@thmain
Last active May 28, 2023 21:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thmain/3eb38e2db19a99f9b6ef to your computer and use it in GitHub Desktop.
Save thmain/3eb38e2db19a99f9b6ef to your computer and use it in GitHub Desktop.
public class ReverseLinkedList {
static class Node{
public int data;
public Node next;
public Node(int data){
this.data = data;
this.next = null;
}
}
public static Node reverseIterative(Node head){
Node currNode = head;
Node nextNode = null;
Node prevNode = null;
while(currNode!=null){
nextNode = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = nextNode;
}
head = prevNode;
return head;
}
public static void display(Node head) {
Node currNode = head;
while (currNode != null) {
System.out.print("->" + currNode.data);
currNode = currNode.next;
}
System.out.println();
}
public static void main (String[] args){
Node head = new Node(5);
head.next = new Node(4);
head.next.next = new Node(3);
head.next.next.next = new Node(2);
display(head);
Node new_head = reverseIterative(head);
System.out.println("reversed");
display(new_head);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment