My Java solution with O(n) time


  • 0
    H
    public ListNode rotateRight(ListNode head, int k) {
        
        if(head == null)
            return head;
        if(head.next == null)
            return head;
        if(k == 0)
            return head;
       
        List<ListNode> list = new ArrayList<>();
        ListNode current = head;
        while(current != null){
            list.add(current);
            current = current.next;
        }
       
        if(k >= list.size()){
            if(k % list.size() == 0)
                return head;
            k = k % list.size();
        }
        
        ListNode oriFirst = list.get(0);
        ListNode newFirst = list.get(list.size() - k);
        ListNode oriTail = list.get(list.size() - 1);
        ListNode newTail = list.get(list.size() - 1 - k);
        newTail.next = null;
        oriTail.next = oriFirst;
        
        return newFirst;
    }

  • 0
    W

    My ugly java solution, my god, how i could write beautiful code, keep practice

    public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || head.next == null || k == 0){
            return head;
        }
        
        int length = 0;
        ListNode temp = head;
        while(temp != null){
            length++;
            temp = temp.next;
        }
        k = k % length;
        if(k == 0){
            return head;
        }
        int index = length - k;
        ListNode pre = head;
        ListNode cur = head;
        for(int i = 0; i < index; i++){
            pre = cur;
            cur = cur.next;
        }
        pre.next = null;
        ListNode last = cur;
        while(last.next != null){
            last = last.next;
        }
        last.next = head;
        return cur;
    }
    

    }


Log in to reply
 

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