File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ package easy ;
2
+
3
+ import utils .CommonUtils ;
4
+ import classes .ListNode ;
5
+
6
+ public class ReverseLinkedList {
7
+ //there's no reversion if the list is null or it contains only one node, so at a minimum, there should be 2 nodes
8
+ public ListNode reverseList (ListNode head ) {
9
+ ListNode newHead = null ;
10
+ while (head != null ){
11
+ ListNode next = head .next ;
12
+ head .next = newHead ;
13
+ newHead = head ;
14
+ head = next ;
15
+ }
16
+ return newHead ;
17
+ }
18
+
19
+ public static void main (String ...strings ){
20
+ ReverseLinkedList test = new ReverseLinkedList ();
21
+ ListNode head = new ListNode (1 );
22
+ head .next = new ListNode (2 );
23
+ head .next .next = new ListNode (3 );
24
+ head .next .next .next = new ListNode (4 );
25
+ head .next .next .next .next = new ListNode (5 );
26
+ CommonUtils .printList (head );
27
+ ListNode result = test .reverseList (head );
28
+ CommonUtils .printList (result );
29
+ }
30
+
31
+ }
You can’t perform that action at this time.
0 commit comments