首页 > 其他 > 详细

Rotate List

时间:2014-02-15 01:41:38      阅读:359      评论:0      收藏:0      [点我收藏+]

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.

 

ref: http://fisherlei.blogspot.com/2013/01/leetcode-rotate-list.html

首先从head开始跑,直到最后一个节点,这时可以得出链表长度len。然后将尾指针指向头指针,将整个圈连起来,接着往前跑len – k%len,从这里断开,就是要求的结果了。

 

bubuko.com,布布扣
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        
        if(head == null || n == 0) return head;
        
        ListNode p = head;
        int len = 1;
        while(p.next != null){
            len++;
            p = p.next;
        }
        p.next = head;
        
        int steps = len - n%len;
        while(steps > 0){
            p = p.next;
            steps--;
        }
        
        head = p.next;
        p.next = null;
        return head;
    }
}
bubuko.com,布布扣

Rotate List

原文:http://www.cnblogs.com/RazerLu/p/3549268.html

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