1/*
2public class ListNode {
3 public int val;
4 public ListNode next;
5 public ListNode(int x) { val = x; next = null; }
6}
7*/
8
9public static ListNode[] reverse_linked_list(ListNode head) {
10
11 ListNode prev = null;
12 ListNode current = head;
13 ListNode next;
14
15 ListNode tail = head;
16
17 while (current != null) {
18
19 next = current.next;
20 current.next = prev;
21 prev = current;
22 current = next;
23 }
24
25 head = prev;
26
27 ListNode[] result = {head, tail};
28
29 return result;
30}
1Easiest way
2
3
4public static LinkedList reverse(LinkedList head) {
5 LinkedList prevAddress = null;
6 LinkedList currentAddress = head;
7 LinkedList nextAddress = head.next;
8
9 while(nextAddress!=null) {
10 currentAddress.next = prevAddress;
11 prevAddress = currentAddress;
12 currentAddress = nextAddress;
13 nextAddress= currentAddress.next;
14 currentAddress.next = prevAddress;
15 }
16 head = currentAddress;
17 return head;
18 }
19
20Just try to visualize its all about pointers game. :-)
21 NO GFG ANSWER