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

Commitfa4cbba

Browse files
committed
list
1 parent08ca067 commitfa4cbba

File tree

1 file changed

+105
-0
lines changed

1 file changed

+105
-0
lines changed

‎list/SwapPairs3.java

Lines changed: 105 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,105 @@
1+
packageAlgorithms.list;
2+
3+
importAlgorithms.algorithm.others.ListNode;
4+
5+
/**
6+
* Definition for singly-linked list.
7+
* public class ListNode {
8+
* int val;
9+
* ListNode next;
10+
* ListNode(int x) {
11+
* val = x;
12+
* next = null;
13+
* }
14+
* }
15+
*/
16+
publicclassSwapPairs3 {
17+
// Solution 1: the recursion version.
18+
publicListNodeswapPairs1(ListNodehead) {
19+
if (head ==null) {
20+
returnnull;
21+
}
22+
23+
returnrec(head);
24+
}
25+
26+
publicListNoderec(ListNodehead) {
27+
if (head ==null ||head.next ==null) {
28+
returnhead;
29+
}
30+
31+
ListNodenext =head.next.next;
32+
33+
// 翻转后面的链表
34+
next =rec(next);
35+
36+
// store the new head.
37+
ListNodetmp =head.next;
38+
39+
// reverse the two nodes.
40+
head.next =next;
41+
tmp.next =head;
42+
43+
returntmp;
44+
}
45+
46+
// Solution 2: the iteration version.
47+
publicListNodeswapPairs(ListNodehead) {
48+
// 如果小于2个元素,不需要任何操作
49+
if (head ==null ||head.next ==null) {
50+
returnhead;
51+
}
52+
53+
ListNodedummy =newListNode(0);
54+
dummy.next =head;
55+
56+
// The node before the reverse area;
57+
ListNodepre =dummy;
58+
59+
while (pre.next !=null &&pre.next.next !=null) {
60+
// The last node of the reverse area;
61+
ListNodetail =pre.next.next;
62+
63+
ListNodetmp =pre.next;
64+
pre.next =tail;
65+
66+
ListNodenext =tail.next;
67+
tail.next =tmp;
68+
tmp.next =next;
69+
70+
// move forward the pre node.
71+
pre =tmp;
72+
}
73+
74+
returndummy.next;
75+
}
76+
77+
// Solution 3: the iteration version.
78+
publicListNodeswapPairs3(ListNodehead) {
79+
// 如果小于2个元素,不需要任何操作
80+
if (head ==null ||head.next ==null) {
81+
returnhead;
82+
}
83+
84+
ListNodedummy =newListNode(0);
85+
dummy.next =head;
86+
87+
// The node before the reverse area;
88+
ListNodepre =dummy;
89+
90+
while (pre.next !=null &&pre.next.next !=null) {
91+
ListNodenext =pre.next.next.next;
92+
93+
ListNodetmp =pre.next;
94+
pre.next =pre.next.next;
95+
pre.next.next =tmp;
96+
97+
tmp.next =next;
98+
99+
// move forward the pre node.
100+
pre =tmp;
101+
}
102+
103+
returndummy.next;
104+
}
105+
}

0 commit comments

Comments
 (0)

[8]ページ先頭

©2009-2025 Movatter.jp