-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSwapPairs.java
More file actions
41 lines (29 loc) · 762 Bytes
/
Copy pathSwapPairs.java
File metadata and controls
41 lines (29 loc) · 762 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
37
38
39
40
41
package org.example;
public class SwapPairs {
public ListNode swapPairs(ListNode head) {
if (head == null) {
return null;
}
ListNode dummy = new ListNode();
dummy.next = head;
exchange(head,dummy);
return dummy.next;
}
private ListNode exchange(ListNode head, ListNode pre) {
if (head == null) {
return null;
}
if (head.next == null) {
return head;
}
ListNode first = head;
ListNode second = head.next;
ListNode third = second.next;
pre.next = second;
second.next = first;
first.next = third;
pre = first;
exchange(third,pre);
return second;
}
}