Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit35cd0c5

Browse files
authored
add solution and test case for 1721 (#146)
* added solution and test case for 1721* merged with master* removed comments and initialized variables on new lines
1 parent02ed0de commit35cd0c5

File tree

2 files changed

+76
-0
lines changed

2 files changed

+76
-0
lines changed

‎src/main/java/com/fishercoder/solutions/_1721.java

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,4 +30,42 @@ public ListNode swapNodes(ListNode head, int k) {
3030
returntmp.next;
3131
}
3232
}
33+
publicstaticclassSolution2 {
34+
publicListNodeswapNodes(ListNodehead,intk) {
35+
if(head ==null ||head.next ==null){
36+
returnhead;
37+
}
38+
39+
// find length of list
40+
intn =0;
41+
ListNodecurrent =head;
42+
while(current !=null){
43+
current =current.next;
44+
n++;
45+
}
46+
47+
intnums[] =newint[n];
48+
current =head;
49+
inti =0;
50+
while(current !=null){
51+
nums[i++] =current.val;
52+
current =current.next;
53+
}
54+
intfirstIndex =0;
55+
intsecondIndex =0;
56+
firstIndex =k;
57+
secondIndex =n-k;
58+
inttemp =nums[firstIndex-1];
59+
nums[firstIndex-1] =nums[secondIndex];
60+
nums[secondIndex] =temp;
61+
ListNodedummy =newListNode(-1);
62+
current =dummy;
63+
for(i =0;i<n;i++){
64+
ListNodenode =newListNode(nums[i]);
65+
current.next =node;
66+
current =current.next;
67+
}
68+
returndummy.next;
69+
}
70+
}
3371
}
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
packagecom.fishercoder;
2+
3+
importcom.fishercoder.common.classes.ListNode;
4+
importcom.fishercoder.solutions._1721;
5+
importorg.junit.BeforeClass;
6+
importorg.junit.Test;
7+
8+
importstaticorg.junit.Assert.assertEquals;
9+
10+
publicclass_1721Test {
11+
privatestatic_1721.Solution2solution2;
12+
privatestaticListNodeexpected;
13+
privatestaticListNodenode;
14+
privatestaticintk;
15+
16+
@BeforeClass
17+
publicstaticvoidsetup() {
18+
solution2 =new_1721.Solution2();
19+
}
20+
21+
@Test
22+
publicvoidtest1() {
23+
node =newListNode(1);
24+
node.next =newListNode(2);
25+
node.next.next =newListNode(3);
26+
node.next.next.next =newListNode(4);
27+
node.next.next.next.next =newListNode(5);
28+
29+
expected =newListNode(1);
30+
expected.next =newListNode(4);
31+
expected.next.next =newListNode(3);
32+
expected.next.next.next =newListNode(2);
33+
expected.next.next.next.next =newListNode(5);
34+
35+
k =2;
36+
assertEquals(expected,solution2.swapNodes(node,k));
37+
}
38+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp