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

Swap Nodes in Pairs

2015-07-19 15:59 531 查看
Problem: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.

处理链表中的两个节点,同时需要记录这两个节点的前一个和下一个节点。

例如处理上面的1,2,需要使用两个变量记录1之前的节点,2之后的节点3。

public ListNode swapPairs(ListNode head) {
ListNode p=new ListNode(0);
p.next=head;
ListNode pre=p;
if(head==null||head.next==null)
return head;
while(pre.next!=null&&pre.next.next!=null){
ListNode t=pre;
pre=pre.next;
t.next=pre.next;

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