public class TurnBackLinkedList {
public static void main(String[] args) {
Node head = new Node();
Node cur = head;
for(int i = 0; i < 10; i++) {
int value = (int) (Math.random()*100);
Node newNode = new Node();
newNode.value = value;
cur.next = newNode;
cur = cur.next;
}
printLinkedList(head);
Node newHead = turnBackLinkedList(head);
printLinkedList(newHead);
}
static Node turnBackLinkedList(Node head){
Node newHead = head;
Node oldHead = head.next;
newHead.next = null;
while(oldHead != null) {
Node temp = oldHead.next;
oldHead.next = newHead;
newHead = oldHead;
oldHead = temp;
}
return newHead;
}
static class Node {
Node next;
int value;
}
static void printLinkedList(Node head) {
Node cur = head;
while(cur != null) {
System.out.print(cur.value + " ");
cur = cur.next;
}
System.out.println();
}
}