您的位置:首页 > Web前端 > Node.js

Swap Nodes in Pairs(easy)

2016-06-01 17:37 323 查看
题目

Given a linked list, swap every two adjacent nodes and return its head.

For example,

Given 
1->2->3->4
, you should return the list as 
2->1->4->3
.

Your algorithm should use only constant space. You may not modify the values in the list, only nodes itself can be changed.

题意

     将链表临接的元素交换

分析

     每次读两个节点插入新链表,因为是指针操作,不占用额外空间。最后需要把tail指针的next设为NULL。例如链表为p1->p2->p3->p4的情况,如果最后不修改p3->next,那么就会出现一个环:p2->p1->p4->p3->p4->...
就是每次跳两个节点,后一个接到前面,前一个接到后一个的后面,最后现在的后一个(也就是原来的前一个)接到下下个结点(如果没有则接到下一个)

这道题中用了一个辅助指针作为表头,这是链表中比较常用的小技巧,因为这样可以避免处理head的边界情况,一般来说要求的结果表头会有变化的会经常用这个技巧,大家以后会经常遇到。
因为这是一遍过的算法,时间复杂度明显是O(n),空间复杂度是O(1)。

实现

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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: