File tree Expand file tree Collapse file tree 2 files changed +76
-0
lines changed
main/java/com/fishercoder/solutions
test/java/com/fishercoder Expand file tree Collapse file tree 2 files changed +76
-0
lines changed Original file line number Diff line number Diff line change @@ -30,4 +30,42 @@ public ListNode swapNodes(ListNode head, int k) {
3030 return tmp .next ;
3131 }
3232 }
33+ public static class Solution2 {
34+ public ListNode swapNodes (ListNode head , int k ) {
35+ if (head == null || head .next == null ){
36+ return head ;
37+ }
38+
39+ // find length of list
40+ int n = 0 ;
41+ ListNode current = head ;
42+ while (current != null ){
43+ current = current .next ;
44+ n ++;
45+ }
46+
47+ int nums [] = new int [n ];
48+ current = head ;
49+ int i = 0 ;
50+ while (current != null ){
51+ nums [i ++] = current .val ;
52+ current = current .next ;
53+ }
54+ int firstIndex = 0 ;
55+ int secondIndex = 0 ;
56+ firstIndex = k ;
57+ secondIndex = n -k ;
58+ int temp = nums [firstIndex -1 ];
59+ nums [firstIndex -1 ] = nums [secondIndex ];
60+ nums [secondIndex ] = temp ;
61+ ListNode dummy = new ListNode (-1 );
62+ current = dummy ;
63+ for (i = 0 ; i <n ; i ++){
64+ ListNode node = new ListNode (nums [i ]);
65+ current .next = node ;
66+ current = current .next ;
67+ }
68+ return dummy .next ;
69+ }
70+ }
3371}
Original file line number Diff line number Diff line change 1+ package com .fishercoder ;
2+
3+ import com .fishercoder .common .classes .ListNode ;
4+ import com .fishercoder .solutions ._1721 ;
5+ import org .junit .BeforeClass ;
6+ import org .junit .Test ;
7+
8+ import static org .junit .Assert .assertEquals ;
9+
10+ public class _1721Test {
11+ private static _1721 .Solution2 solution2 ;
12+ private static ListNode expected ;
13+ private static ListNode node ;
14+ private static int k ;
15+
16+ @ BeforeClass
17+ public static void setup () {
18+ solution2 = new _1721 .Solution2 ();
19+ }
20+
21+ @ Test
22+ public void test1 () {
23+ node = new ListNode (1 );
24+ node .next = new ListNode (2 );
25+ node .next .next = new ListNode (3 );
26+ node .next .next .next = new ListNode (4 );
27+ node .next .next .next .next = new ListNode (5 );
28+
29+ expected = new ListNode (1 );
30+ expected .next = new ListNode (4 );
31+ expected .next .next = new ListNode (3 );
32+ expected .next .next .next = new ListNode (2 );
33+ expected .next .next .next .next = new ListNode (5 );
34+
35+ k = 2 ;
36+ assertEquals (expected , solution2 .swapNodes (node , k ));
37+ }
38+ }
You can’t perform that action at this time.
0 commit comments