Mine looks terrible.(Java)


  • 0
    L

    When got the question, my instinct idea is to find the position and relink the nodes. From the forum,
    circle the lists and find the newhead is so awesome. Code is also shown below.

    /**
     * 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 || k ==0) return head;
            int len =0;
            ListNode p= head;
            ListNode pre = head;
            ListNode dummy = new ListNode(0);
            dummy.next = head;
            while(p != null){
                len++;
                pre = p;
                p=p.next;
            }
            k = k % len;
            if(k== 0) return head;
            ListNode fast =head;
            for(int i =0; i<=k; i++){
                fast = fast.next;
            }
            ListNode slow = head;
            while(fast!= null){
                slow = slow.next;
                fast = fast.next;
            }
            ListNode tmp = slow.next;
            slow.next = null;
            pre.next = dummy.next;
            dummy.next = tmp;
            return dummy.next;
            
        }
    }
    

    The code below is to cycle the list and refind the new head; hope it may help you. For me the tricky
    part is when dealing with node, you have to find its previous node inorder to conduct some operation like

    ListNode tmp = node.next;
    node.next = ...;
    dummy.next = tmp;
    // something like that.
    
    public class Solution {
        public ListNode rotateRight(ListNode head, int k) {
            if(head == null ) return head;
            
            
            int len = 1;
            ListNode p = head;
            while(p.next != null){
                len ++;
                p = p.next;
            }
            p.next = head;
            
            if(k %len != 0){
                k = k %len;
                for(int i =0; i< len - k; i++){
                    p = p.next;
                }
            }
            ListNode nhead = p.next;
            p.next = null;
            return nhead;
            
        }
    }
    

Log in to reply
 

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