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

LeetCode--24. Swap Nodes in Pairs

2016-03-23 22:30 567 查看
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.

Analysis:

题目意思:

给定一个链表,调换每两个相邻节点,并返回其头部。

例如, 给定 1->2->3->4, 你应该返回的链表是 2->1->4->3。

你的算法必须使用唯一不变的空间。

你也不能修改列表中的值,只有节点本身是可以改变的。

链表问题,这个题需要多用一个节点,一个标记一对中的第一个,一个标记一对中的第二个。

Answer:

/**
* Definition for singly-linked list.
* public class ListNode {
*     int val;
*     ListNode next;
*     ListNode(int x) { val = x; }
* }
*/
public class Solution {
public ListNode swapPairs(ListNode head) {
if(head==null || head.next==null) return head;
ListNode pre=new ListNode(0);
pre.next= head;
ListNode p=pre;
while(p.next!=null && p.next.next!=null){
//
ListNode t1 = p;
p=p.next;
t1.next=p.next;
//
ListNode t2 = p.next;
p.next.next =p;
p.next=t2;
}
return pre.next;
}
}


经验:

1.一般链表的问题如果会返回链表(从头开始)则最好用以下的三行代码,helper来记住链表开头,p来进行运算;而且p = helper后p和helper指向的下一个节点一致。

ListNode helper = new ListNode(0);
helper.next = head;
ListNode p = helper;


2.p = p.next这句语句就是将p的指针后移(因为是对p操作的),p.next = t2这句与句就是把p的指向变换(因为是对p.next操作的),

p.next.next = p就是对p的下一个节点的指向操作。

3.while(p.next != null && p.next.next != null)这句语句来进行下一个节点是否满足情况的分析。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: