forked from algorithm016-algorithm016/algorithm016
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolution1.java
More file actions
53 lines (48 loc) · 1.46 KB
/
Solution1.java
File metadata and controls
53 lines (48 loc) · 1.46 KB
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
package src.leetcode;
import src.common.node.ListNode;
/**
* 两两交换链表中的节点
*/
class Solution1 {
public static void main(String[] args) {
ListNode head = ListNode.genNextNode(new int[]{1,2,3,4});
ListNode listNode = new Solution1().swapPairsDG_Reverse(head);
System.out.println(listNode);
}
public ListNode swapPairsDG_Reverse(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode next = head.next;
head.next = swapPairsDG_Reverse(next.next);
next.next = head;
//返回链表头结点
return next;
}
public ListNode swapPairsDG_Order(ListNode head) {
if (head == null || head.next ==null ) {
return null;
}
ListNode nextNode = head.next.next;
ListNode next = head.next;
next.next = head;
head.next = swapPairsDG_Order(nextNode);
//返回链表头结点
return next;
}
//遍历 不懂
public ListNode swapPairs(ListNode head) {
ListNode pre = ListNode.genNextNode(new int[]{0});
pre.next = head;
ListNode temp = pre;
while(temp.next != null && temp.next.next != null) {
ListNode start = temp.next;
ListNode end = temp.next.next;
temp.next = end;
start.next = end.next;
end.next = start;
temp = start;
}
return pre.next;
}
}