FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
algorithm/Week_01/id_108/LeetCode_24_108.java at master · feixiangcode/algorithm · GitHub
feixiangcode
/
algorithm
Public
forked from
algorithm001/algorithm
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
algorithm
/
Week_01
/
id_108
/
LeetCode_24_108.java
Copy path
More file actions
More file actions
Latest commit
History
History
History
87 lines (85 loc) · 2.68 KB
Breadcrumbs
algorithm
/
Week_01
/
id_108
/
LeetCode_24_108.java
Copy path
File metadata and controls
87 lines (85 loc) · 2.68 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
/**
* @author zhangruihao.zhang
* @version v1.0.0
* @since 2019/04/20
*/
public
class
LeetCode_24_108
{
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class
Solution1
{
public
ListNode
swapPairs
(
ListNode
head
) {
if
(
head
==
null
||
head
.
next
==
null
){
return
head
;
}
//标识要交换的第一个节点
ListNode
first
=
head
;
//标识要交换的第二个节点
ListNode
second
=
head
.
next
;
//标识下一组要交换的节点对
ListNode
cur
=
second
.
next
;
//交换
first
.
next
=
cur
;
second
.
next
=
first
;
head
=
second
;
ListNode
pre
=
first
;
//下一组
first
=
cur
;
second
=
cur
==
null
||
cur
.
next
==
null
?
null
:
cur
.
next
;
cur
=
second
==
null
?
null
:
second
.
next
;
while
(
first
!=
null
&&
second
!=
null
){
//交换
first
.
next
=
cur
;
second
.
next
=
first
;
pre
.
next
=
second
;
pre
=
first
;
//下一组
first
=
cur
;
second
=
cur
==
null
||
cur
.
next
==
null
?
null
:
cur
.
next
;
cur
=
second
==
null
?
null
:
second
.
next
;
}
return
head
;
}
}
class
Solution2
{
public
ListNode
swapPairs
(
ListNode
head
) {
if
(
head
==
null
||
head
.
next
==
null
){
return
head
;
}
//标识要交换的第一个节点
ListNode
first
=
head
;
//标识要交换的第二个节点
ListNode
second
=
head
.
next
;
//标识下一组要交换的节点对
ListNode
cur
=
second
.
next
;
//初始化前节点
ListNode
pre
=
null
;
//第一次交换
first
.
next
=
cur
;
second
.
next
=
first
;
head
=
second
;
while
(
true
){
pre
=
first
;
first
=
cur
;
second
=
cur
==
null
||
cur
.
next
==
null
?
null
:
cur
.
next
;
cur
=
second
==
null
?
null
:
second
.
next
;
if
(
first
==
null
||
second
==
null
){
break
;
}
swap
(
pre
,
first
,
second
,
cur
);
}
return
head
;
}
private
void
swap
(
ListNode
pre
,
ListNode
first
,
ListNode
second
,
ListNode
cur
){
//交换
first
.
next
=
cur
;
second
.
next
=
first
;
pre
.
next
=
second
;
}
}
}
Back
|
FazBrowse Home
|
New Git URL