-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLeetCode24.java
More file actions
32 lines (26 loc) · 929 Bytes
/
LeetCode24.java
File metadata and controls
32 lines (26 loc) · 929 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
import util.ListNode;
public class LeetCode24 {
public static void main(String[] args) {
// 输入:head = [1,2,3,4]
// 输出:[2,1,4,3]
System.out.println(new Solution24().swapPairs(ListNode.buildLinkedList(new Integer[] { 1, 2, 3, 4 })));
// 输入:head = []
// 输出:[]
System.out.println(new Solution24().swapPairs(ListNode.buildLinkedList(new Integer[] {})));
// 输入:head = [1]
// 输出:[1]
System.out.println(new Solution24().swapPairs(ListNode.buildLinkedList(new Integer[] { 1 })));
}
}
class Solution24 {
public ListNode swapPairs(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode oldHead = head;
ListNode newHead = head.next;
oldHead.next = swapPairs(newHead.next);
newHead.next = oldHead;
return newHead;
}
}