My Easy Understanding 16ms Solution With Two Pointer


  • 0
    B
    public ListNode rotateRight(ListNode head, int k) {
            if (head == null||k==0) return head;
            ListNode forwordSearcher = head;
            ListNode kSearcher = head;
            ListNode lengthSearcher = head;
            int count=0;
            while(lengthSearcher!=null){
                count++;
                lengthSearcher = lengthSearcher.next;
            }
            k = k % count;
            if (k==0) return head;
            for(int i=0;i<k;i++){
                kSearcher = kSearcher.next;
            }
            while(kSearcher.next!=null){
                kSearcher = kSearcher.next;
                forwordSearcher = forwordSearcher.next;
            }
            ListNode newHead = forwordSearcher.next;
            forwordSearcher.next = kSearcher.next;
            kSearcher.next = head;
            return newHead;
        }

Log in to reply
 

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