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

【链表&交换邻节点】Swap Nodes in Pairs

2014-04-05 23:28 453 查看
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.
链表操作,注意头结点,交换的pre节点是否为null
public class Solution {
public ListNode swapPairs(ListNode head) {
int k = 0;
ListNode p = head, pre=null;
while(p != null){
ListNode r = null;
k++;
if(k%2 == 0){//r指向要交换的第一节点,p指向要交换的第二个节点,pre指向第一个节点的前一个节点
if(pre == null){
r = head;
r.next = p.next;
p.next = r;
head = p;
pre = r;
}
else{
r = pre.next;
r.next = p.next;
p.next = r;
pre.next = p;
pre = r;
}
p = r.next;
}
else p = p.next;
}
return head;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: