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

24. Swap Nodes in Pairs

2016-09-13 21:13 246 查看
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.

时间复杂度:O(N)

思路: 从前往后,依次交换相邻的2个node,注意的是节点的交换过程.

public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;
ListNode start=new ListNode(0);
start.next=head;

ListNode temp=start;
ListNode p1,p2;
while(temp.next!=null&&temp.next.next!=null){
p1=temp.next;
p2=p1.next;
temp.next=p2;
p1.next=p2.next;
p2.next=p1;
temp=p1;
}
return start.next;

递归解法:: 求解从第一个开始的list和求解从第3个开始的list步骤是一样的,因此可以使用递归;

public ListNode swapPairs(ListNode head) {
if(head==null||head.next==null)
return head;

ListNode start=head.next;

head.next=swapPairs(head.next.next);
start.next=head;
return start;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: