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

Commit8b9c165

Browse files
add a solution for 24
1 parent9fbb852 commit8b9c165

File tree

2 files changed

+45
-2
lines changed

2 files changed

+45
-2
lines changed

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

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44

55
publicclass_24 {
66
publicstaticclassSolution1 {
7+
/**
8+
* Recursive solution.
9+
*/
710
publicListNodeswapPairs(ListNodehead) {
811
if (head ==null ||head.next ==null) {
912
returnhead;
@@ -16,4 +19,32 @@ public ListNode swapPairs(ListNode head) {
1619
}
1720
}
1821

22+
publicstaticclassSolution2 {
23+
/**
24+
* Iterative approach:
25+
* My completely original on 10/24/2021.
26+
*/
27+
publicListNodeswapPairs(ListNodehead) {
28+
ListNodepre =newListNode(-1);
29+
pre.next =head;
30+
ListNodetmp =pre;
31+
while (head !=null) {
32+
ListNodethird;
33+
ListNodefirst =head;
34+
ListNodesecond =head.next;
35+
if (second ==null) {
36+
break;
37+
}else {
38+
third =head.next.next;
39+
second.next =first;
40+
first.next =third;
41+
tmp.next =second;
42+
tmp =tmp.next.next;
43+
}
44+
head =third;
45+
}
46+
returnpre.next;
47+
}
48+
}
49+
1950
}
Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,39 @@
11
packagecom.fishercoder;
22

33
importcom.fishercoder.common.classes.ListNode;
4-
importcom.fishercoder.common.utils.CommonUtils;
54
importcom.fishercoder.common.utils.LinkedListUtils;
65
importcom.fishercoder.solutions._24;
76
importorg.junit.BeforeClass;
87
importorg.junit.Test;
98

109
importjava.util.Arrays;
1110

11+
importstaticorg.junit.Assert.assertEquals;
12+
1213
publicclass_24Test {
1314
privatestatic_24.Solution1solution1;
15+
privatestatic_24.Solution2solution2;
1416
privatestaticListNodehead;
17+
privatestaticListNodeexpected;
1518

1619
@BeforeClass
1720
publicstaticvoidsetup() {
1821
solution1 =new_24.Solution1();
22+
solution2 =new_24.Solution2();
1923
}
2024

2125
@Test
2226
publicvoidtest1() {
2327
head =LinkedListUtils.createSinglyLinkedList(Arrays.asList(1,2,3,4));
24-
CommonUtils.printList(solution1.swapPairs(head));
28+
expected =LinkedListUtils.createSinglyLinkedList(Arrays.asList(2,1,4,3));
29+
assertEquals(expected,solution1.swapPairs(head));
30+
}
31+
32+
@Test
33+
publicvoidtest2() {
34+
head =LinkedListUtils.createSinglyLinkedList(Arrays.asList(1,2,3,4));
35+
expected =LinkedListUtils.createSinglyLinkedList(Arrays.asList(2,1,4,3));
36+
assertEquals(expected,solution2.swapPairs(head));
2537
}
2638

2739
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp