Created
March 5, 2023 05:24
-
-
Save shaobos/f1e1f1a571bba50df1912899a215ecea to your computer and use it in GitHub Desktop.
Reverse linked list - Java
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 Node { | |
int val; | |
Node next; | |
public Node(int val) { | |
this.val = val; | |
this.next = null; | |
} | |
} | |
public class LinkedList { | |
Node head; | |
public void add(int val) { | |
Node node = new Node(val); | |
if (head == null) { | |
head = node; | |
} else { | |
Node curr = head; | |
while (curr.next != null) { | |
curr = curr.next; | |
} | |
curr.next = node; | |
} | |
} | |
public void reverse() { | |
// TODO: please implement | |
} | |
public void print() { | |
Node curr = head; | |
while (curr != null) { | |
System.out.print(curr.val + " "); | |
curr = curr.next; | |
} | |
System.out.println(); | |
} | |
} | |
public class Main { | |
public static void main(String[] args) { | |
LinkedList list = new LinkedList(); | |
list.add(1); | |
list.add(2); | |
list.add(3); | |
list.add(4); | |
list.add(5); | |
System.out.println("Original list:"); | |
list.print(); | |
list.reverse(); | |
System.out.println("Reversed list:"); | |
list.print(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment