美文网首页
61.旋转链表

61.旋转链表

作者: _道友请留步_ | 来源:发表于2018-05-14 20:09 被阅读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;
        }
    }
    

    相关文章

      网友评论

          本文标题:61.旋转链表

          本文链接:https://www.haomeiwen.com/subject/xazjdftx.html