Sunday, February 25, 2018

170. Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.

Wrong solution 1:
public ListNode rotateRight(ListNode head, int k) {
        // write your code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head;
        ListNode fast = head;
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        fast.next = head;
        head = slow.next;
        slow.next = null;
        
        return head;

    }


WA

if k is greater than the length of the linked list, it needs to mod the length of the linked list


Solution 2:
  public ListNode rotateRight(ListNode head, int k) {
        // write your code here
        if (head == null || head.next == null) {
            return head;
        }
        ListNode slow = head;//new ListNode(0);
        //slow.next = head;
        ListNode fast = head;
        int length = getLength(head);
        for (int i = 0; i < (k % length); i++) {
            fast = fast.next;
        }
        
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        fast.next = head;
        head = slow.next;
        slow.next = null;
        return head;
    }
    
    private int getLength(ListNode head) {
        int length = 0;
        ListNode dummy = head;
        while(dummy != null) {
            length++;
            dummy = dummy.next;
        }
        return length;
    }

    

No comments:

Post a Comment

4. Ugly Number

1*2(t2) 2*2 3*2 (t3)1*3 2*3 3*3 (t5)1*5 2*5 3*5 1*2 2*2(t2) 3*2 1*3(t3) 2*3 3*3 (t5)1*5 2*5 3*5 Solution: public int nthUglyNumbe...