The simplest way to reverse a linked list is to use a stack, put it on the stack and take it out, but this operation uses O(N) space complexity.. You can do it in order one.

Public class C08_RevolveLinked1 {// public static class Node {int value; Node next; public Node(int value) { this.value = value; }} public static Node reverseList(Node head) {Node next = null; Node pre = null; while (head ! = null) { next = head.next; Head. Next = pre; // Set the next node of the head node to null (pre) pre = head; // head = next; // The head node becomes its next node (moved down one bit)} return pre; // Since head is a loop that exits when empty, Public static void printList(Node head) {system.out. print("Linked List:"); while (head ! = null) { System.out.print(head.value + " "); head = head.next; } System.out.println(); } / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / / two-way linked list public static class DoubleNode {int value. DoubleNode last; DoubleNode next; public DoubleNode(int value) { this.value = value; Public static reverseList(reverblenode head) {reverblenode pre = null; DoubleNode next = null; while (head ! = null) { next = head.next; head.next = pre; head.last = next; pre = head; head = next; } return pre; } // Print bidirectional linked list // print forward and reverse!! public static void printList(DoubleNode head) { System.out.print("Double Linked List: "); DoubleNode end = null; while (head ! = null) { System.out.print(head.value + " "); end = head; head = head.next; } System.out.print(" || "); while (end ! = null) { System.out.print(end.value + " "); end = end.last; } System.out.println(); } public static void main(String[] args) { Node head1 = new Node(1); head1.next = new Node(2); head1.next.next = new Node(3); printList(head1); head1 = reverseList(head1); printList(head1); System.out.println("=================="); DoubleNode head2 = new DoubleNode(1); head2.next = new DoubleNode(2); head2.next.last = head2; head2.next.next = new DoubleNode(3); head2.next.next.last = head2.next; head2.next.next.next = new DoubleNode(4); head2.next.next.next.last = head2.next.next; printList(head2); printList(reverseList(head2)); }}Copy the code