这道题属于链表操作的题目,思路比较清晰,就是每次跳两个节点,后一个接到前面,前一个接到后一个的后面,最后现在的后一个(也就是原来的前一个)接到下下个结点(如果没有则接到下一个)。代码如下:
public ListNode swapPairs(ListNode head) {
if(head == null)
return null;
ListNode helper = new ListNode(0);
helper.next = head;
ListNode pre = helper;
ListNode cur = head;
while(cur!=null && cur.next!=null)
{
ListNode next = cur.next.next;
cur.next.next = cur;
pre.next = cur.next;
if(next!=null && next.next!=null)
cur.next = next.next;
else
cur.next = next;
pre = cur;
cur = next;
}
return helper.next;
}
这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧,大家以后会经常遇到。
Swap Nodes in Pairs -- LeetCode,布布扣,bubuko.com
Swap Nodes in Pairs -- LeetCode
原文:http://blog.csdn.net/linhuanmars/article/details/19948569