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;
        }
    }
    
    
  • 相关阅读:
    「SPOJ10707」Count on a tree II
    UVA 11021 /概率
    power oj/2360/Change
    POJ1613 147/思维题
    Power oj2498/DP/递推
    HDU4815/计数DP
    444A/CF
    观光公交noip<贪心>
    2014 Shanghai Invitation Contest
    POJ1734/Floyd求最小环
  • 原文地址:https://www.cnblogs.com/Victor-Han/p/5170450.html
Copyright © 2011-2022 走看看