I keep seeing an advertisement saying "you may know how to reverse a linked list, but not system design", so just try to write down how to reverse linked list here.
public class LinkedList {
Node head;
public static void printLinkedList(Node node) {
while(node != null) {
System.out.print(node.value + " ");
node = node.next;
}
}
public static Node reverseLinkedList(Node node) {
Node pre = null;
Node next = null;
Node cur = node;
while(cur != null) {
next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
public static void main(String[] args)
{
LinkedList list = new LinkedList();
list.head = new Node(85);
list.head.next = new Node(75);
list.head.next.next = new Node(55);
list.head.next.next.next = new Node(11);
System.out.println("Order before reversing:");
printLinkedList(list.head);
System.out.println("Order after reversing:");
printLinkedList(reverseLinkedList(list.head));
}
}
class Node {
int value;
Node next;
public Node(int value) {
this.value = value;
this.next = null;
}
}
Comments
Post a Comment