链接
题目描述
1.递归
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null){
return head;
}
if(head.next == null){
return head;
}
ListNode cur = head;
ListNode next = cur.next;
ListNode temp = next.next;
next.next = cur;
cur.next = swapPairs(temp);
return next;
}
}
2.非递归
对当前节点 temp ,去交换当前节点的下两个节点,交换完了把 temp 往后移动
代码
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null){
return head;
}
ListNode pre = new ListNode(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;
}
}