zoukankan      html  css  js  c++  java
  • [LeetCode 061] Rotate List

    Question

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

    Example

    • Given 1->2->3->4->5->NULL and k = 2,
    • return 4->5->1->2->3->NULL.

    Code

    /**
     * Definition for singly-linked list.
     * public class ListNode {
     *     int val;
     *     ListNode next;
     *     ListNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null) {
                return head;
            }
            ListNode anchor = new ListNode(0);
            anchor.next = head;
            int nodeNumber = getNodeNumber(head);
            int step = k % nodeNumber;
            ListNode first = head;
            ListNode second = head;
            while (step > 0) {
                second = second.next;
                step--;
            }
    
            while (second.next != null) {
                first = first.next;
                second = second.next;
            }
            second.next = head;
            anchor.next = first.next;
            first.next = null;
            return anchor.next;
        }
        // calculate the number of node in the linked list
        private int getNodeNumber(ListNode head) {
            int count = 0;
            while (head != null) {
                count++;
                head = head.next;
            }
            return count;
        }
    }
    
    
  • 相关阅读:
    git分布式版本控制(六)
    git分布式版本控制(五)
    git分布式版本控制(四)
    git分布式版本控制(三)
    git分布式版本控制(二)
    git分布式版本控制(一)
    svn版本控制(十)
    svn版本控制(九)
    svn版本控制(八)
    svn版本控制(七)
  • 原文地址:https://www.cnblogs.com/Victor-Han/p/5170450.html
Copyright © 2011-2022 走看看