Last active
May 28, 2023 21:58
-
-
Save thmain/3eb38e2db19a99f9b6ef to your computer and use it in GitHub Desktop.
This file contains 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
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