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.

 

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

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

 

/**
 * 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;
    }
}

 

posted @ 2014-02-14 11:14  Razer.Lu  阅读(607)  评论(0编辑  收藏  举报