迭代法
/**
* 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 dummy = new ListNode(0);
dummy.next = head;
ListNode currentHead = dummy;
ListNode pre = head;
ListNode p = head.next;
ListNode tmp = null;
while(p!=null&&pre!=null)//本题的关键在于找到循环结束的点
{
pre.next = p.next;
p.next = pre;
currentHead.next = p;
currentHead = currentHead.next.next;
tmp = p;
p =pre;
pre = tmp;
if(p.next!=null)
{
p = p.next.next;
pre = pre.next.next;
}
else
{
p = null;
pre = null;
}
}
return dummy.next;
}
}
递归解法:
递归算法的三要点:
class Solution {
public ListNode swapPairs(ListNode head) {
if(head == null || head.next == null){
return head;
}
ListNode next = head.next;
head.next = swapPairs(next.next);
next.next = head;
return next;
}
}