61.旋转链表

2018-05-14  本文已影响0人  _道友请留步_
/**
 * 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 || head.next == null || k == 0){
            return head;
        }
        ListNode root = new ListNode(-1);
        int count = 0;
        for(ListNode node = head; node != null;node = node.next){
            count += 1;
            if(node.next == null){ //end
                node.next = head;
                break;
            }
        }
        
        k = k%count;
        k = count - k;
        count = 0;
        
        for(ListNode node = head; node != null;node = node.next){
            count += 1;
            if(k == count){
                root.next = node.next;
                node.next = null;
                break;
            }
        }
        
        return root.next;
    }
}
上一篇下一篇

猜你喜欢

热点阅读