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

leetcode 24 Swap Nodes in Pairs

2015-01-27 21:37 1501 查看
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.
思路很清晰:就是每次跳两个节点,后一个接到前面,前一个接到后一个的后面,最后现在的后一个(也就是原来的前一个)接到下下个结点(如果没有则接到下一个)
/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) {
*         val = x;
*         next = null;
*     }
* }
*/
public class Solution {
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;  //此时helper和pre共享一个引用,则之前的后一个为helper的后继
if(next!=null && next.next!=null) //最后现在的后一个(原来的前一个)接到下下个结点
cur.next = next.next;
else
cur.next = next;  //如果没有则接到下一个
pre = cur;
cur = next;
}
return helper.next;
}
}

注意:

1. 单链表的所有查询都需要从头结点开始

2. 为了单链表操作方便(标示head方便),小技巧:新建一个结点,该结点的后继指向头。

3. 注意java中引用的概念,除了基本类型的对象"="之后,一般指向同一个空间,只是两个不同的引用

即对于A a, b;如果a=b,则b改变了a也跟着变
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode java