Simple Java Solution


  • 0
    Z
     
    public class Solution {
        public int getLength(ListNode head) {
            int count = 0;
            ListNode tmp = head;
            while (tmp != null) {
                count++;
                tmp = tmp.next;
            }
            return count;
        }
    
        public ListNode rotateRight(ListNode head, int k) {
            if (head == null || head.next == null) {
                return head;
            }
    
            int length = getLength(head);
    
            int n = k % length;
            if (n == 0) {
                return head;
            }
    
            int left = length - n;
            ListNode pre = head;
            while (--left > 0) {
                pre = pre.next;
            }
    
            ListNode curr = pre.next;
            pre.next = null;
    
            ListNode tmp = curr;
            while (tmp.next != null) {
                tmp = tmp.next;
            }
            tmp.next = head;
            return curr;
        }
     
    }
    

  • 0
    T

    hi, my name is LiSi


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.