-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathLeetCode_00024.java
More file actions
36 lines (33 loc) · 975 Bytes
/
LeetCode_00024.java
File metadata and controls
36 lines (33 loc) · 975 Bytes
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
package com.github.jerring.leetcode;
public class LeetCode_00024 {
// 迭代
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode dummy = new ListNode(-1);
dummy.next = head;
ListNode cur = dummy;
while (cur.next != null && cur.next.next != null) {
ListNode first = cur.next;
ListNode second = cur.next.next;
first.next = second.next;
second.next = first;
cur.next = second;
cur = cur.next.next;
}
return dummy.next;
}
// // 递归
// public ListNode swapPairs(ListNode head) {
// if (head == null || head.next == null) {
// return head;
// }
// ListNode p = head;
// head = head.next;
// p.next = head.next;
// head.next = p;
// p.next = swapPairs(p.next);
// return head;
// }
}