Skip to content

Instantly share code, notes, and snippets.

@shaobos
Created March 5, 2023 05:24
Show Gist options
  • Save shaobos/f1e1f1a571bba50df1912899a215ecea to your computer and use it in GitHub Desktop.
Save shaobos/f1e1f1a571bba50df1912899a215ecea to your computer and use it in GitHub Desktop.
Reverse linked list - Java
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