61. Rotate List

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

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL
Explanation:
rotate 1 steps to the right: 5->1->2->3->4->NULL
rotate 2 steps to the right: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL
Explanation:
rotate 1 steps to the right: 2->0->1->NULL
rotate 2 steps to the right: 1->2->0->NULL
rotate 3 steps to the right: 0->1->2->NULL
rotate 4 steps to the right: 2->0->1->NULL
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || k == 0) return head;
        ListNode p = head;
        int length = 1;
        while(p.next != null){
            length++;
            p = p.next;
        }
        k %= length;
        p.next = head;
        int l = length - k;
        ListNode dum = head;
        for(int i = 0; i < l-1; i++){
            dum = dum.next;
        }
        head = dum.next;
        dum.next = null;
        return head;     
    }
}

先遍历一遍,得出链表长度len,注意k可能大于len,因此令k %= len。将尾节点next指针指向首节点,形成一个环,接着往后跑len-k步,从这里断开,就是要求的结果了。

rotate k 步,最后得到的链表最后一个node是第len-k,头节点就是len-k-1.

 
posted @ 2019-08-21 03:52  Schwifty  阅读(142)  评论(0编辑  收藏  举报