File tree Expand file tree Collapse file tree 2 files changed +69
-0
lines changed Expand file tree Collapse file tree 2 files changed +69
-0
lines changed Original file line number Diff line number Diff line change
1
+ package problems .impl ;
2
+
3
+ public class LinkedListReverser {
4
+ public static class ListNode {
5
+ int val ;
6
+ ListNode next ;
7
+ ListNode (int x ) { val = x ; }
8
+ }
9
+
10
+ public static ListNode reverse (ListNode head ) {
11
+ if (head == null ) {
12
+ return null ;
13
+ }
14
+
15
+ ListNode current = head ;
16
+ ListNode previous = null ;
17
+ ListNode next ;
18
+
19
+ while (current .next != null ) {
20
+ next = current .next ;
21
+ current .next = previous ;
22
+ previous = current ;
23
+ current = next ;
24
+ }
25
+
26
+ current .next = previous ;
27
+ return current ;
28
+ }
29
+ }
Original file line number Diff line number Diff line change
1
+ package problems .impl ;
2
+
3
+ import org .junit .Test ;
4
+ import problems .impl .LinkedListReverser .ListNode ;
5
+
6
+ import static org .junit .Assert .*;
7
+
8
+ public class LinkedListReverserTest {
9
+
10
+ @ Test
11
+ public void nullForEmptyLinkedList () {
12
+ assertNull (LinkedListReverser .reverse (null ));
13
+ }
14
+
15
+ @ Test
16
+ public void headForSingleValueList () {
17
+ ListNode head = new ListNode (0 );
18
+
19
+ assertEquals (head , LinkedListReverser .reverse (head ));
20
+ }
21
+
22
+ @ Test
23
+ public void reverseValues () {
24
+ ListNode head = new ListNode (0 );
25
+ ListNode one = new ListNode (1 );
26
+ ListNode two = new ListNode (2 );
27
+ ListNode three = new ListNode (3 );
28
+ head .next = one ;
29
+ one .next = two ;
30
+ two .next = three ;
31
+
32
+ ListNode reversed = LinkedListReverser .reverse (head );
33
+
34
+ assertEquals (3 , reversed .val );
35
+ assertEquals (2 , reversed .next .val );
36
+ assertEquals (1 , reversed .next .next .val );
37
+ assertEquals (0 , reversed .next .next .next .val );
38
+ assertNull (reversed .next .next .next .next );
39
+ }
40
+ }
You can’t perform that action at this time.
0 commit comments