首页 > 其他 > 详细

[LintCode] Rotate List

时间:2015-11-17 12:45:04      阅读:329      评论:0      收藏:0      [点我收藏+]

Rotate List

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

Example

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

 

SOLUTION:

这题挺有意思的,怎么操作还能rotate呢?很简单,先把链表变成一个环,然后将头节点向后移动k个位置就行了!具体实现的时候,有些还是应该注意的,避免重复的绕圈怎么办?先记录链表的长度,然后k % len一下,就是直翻转一次就OK了。记住,一定返回新的头的位置,不要返回老的头的位置。

代码如下:

技术分享
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    /**
     * @param head: the List
     * @param k: rotate to the right k places
     * @return: the list after rotation
     */
    public class CurrNode{
        ListNode node;
        CurrNode(ListNode node){
            this.node = node;
        }
    }
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null){
            return null;
        }
        int len = getLen(head);
        k = k % len;
        ListNode preCut = head;
        ListNode curr = head;
        while (k > 0){
            curr = curr.next;
            k--;
        }
        while (curr.next != null){
            curr = curr.next;
            preCut = preCut.next;
        }
        curr.next = head;
        head = preCut.next;
        preCut.next = null; //关键,不然就不是合法链表了
        return head;
    }
    private int getLen(ListNode head){
        if (head == null){
            return 0;
        }
        int len = 0;
        while (head != null){
            head = head.next;
            len++;
        }
        return len;
    }
}
View Code

 

[LintCode] Rotate List

原文:http://www.cnblogs.com/tritritri/p/4971313.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!