题目链接:
题目描述:
思路:
思路一
示例1中,要交换3和4,应该把指针定位到2,然后执行交换
要交换1和2,就需要一个虚拟头节点,把指针定位到虚拟头节点上
交换的时候:先连好后面的节点,再变换中间的节点
思路二
可以用递归,每次交换两个节点,
实现代码:
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode dummy = new ListNode(0,head);
ListNode cur = dummy;
while(cur.next != null && cur.next.next != null){
ListNode tmp = cur.next;//复制2
cur.next = tmp.next;//1-3
tmp.next = cur.next.next;//2-4
cur.next.next = tmp;//3-2
cur = cur.next.next;//移动指针
}
return dummy.next;
}
}
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode tmp = head.next;
head.next = swapPairs(tmp.next);
tmp.next = head;
return tmp;
}
}