您的位置:首页 > 其它

Leetcode -- Rotate List

2015-01-30 14:20 169 查看
https://oj.leetcode.com/problems/rotate-list/

Given a list, rotate the list to the right by k places, where k is non-negative.

For example:

Given 1->2->3->4->5->NULL and k = 2,

return 4->5->1->2->3->NULL.

public ListNode rotateRight(ListNode head, int n)

这一题,根据题意,我们知道rotate表示的实际上是一种位移,k = 2的时候,链表向右位移两格,以循环的模式。

这一题其实有两种做法,第一种做法是首尾相连,例如例子里,将5.next 连到 1上,假设链表的长度是len, 那么实际上我们就是将头指针的位置,往后移动 len - k个,也就是1挪到了4,然后以4为首,往下找 len - 1次找到新的tail,断尾之。这是第一种做法。要注意的是,k的值是可以超越链表长度本身的。所以在我们获知链表的长度之后,首先要求余, k %= len 来保证k是不会超过链表长度。

第二种做法,不需要首尾相连,可以相当于,将链表本身切成两段,第一段长len - k, 第二段长度为k,然后从第一段-》第二段变成第二段-》第一段这样就可以了。

其实本题并不难,但是边界条件有点多,譬如空链表啦,譬如k刚好等于链表的长度啦。这都是很恶心的事情。

下面给出代码:

public ListNode rotateRight(ListNode head, int n) {
if(head == null)//第一个边界条件 -- 空指针
return null;
ListNode tmp = head;
int length = 1;
while(tmp.next != null){
length++;
tmp = tmp.next;
}
ListNode tail = tmp;
n %= length;
n = n == 0 ? 0 : length - n;
tmp = null;
while(n > 0){
tmp = tmp == null ? head : tmp.next;// 这里其实涉及到第二个边界条件的处理方法,n = 链表长度,这样实际上就完全不需要位移了。
n--;
}
if(tmp != null){//一旦 n = 链表长度,根据刚才的逻辑根本就不会跑进这里。
ListNode res_head = tmp.next;
tmp.next = null;
tail.next = head;
return res_head;
}
return head;//这也就是n = 链表长度才会进来的。返回元头指针即可。
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: