2014年10月1日星期三

[Leetcode] Rotate List

Given a list, rotate the list to the right by k places, where k is non-negative.
For example:
Given 1->2->3->4->5->NULL and k = 2,
return 4->5->1->2->3->NULL.
链表找断点题,注意给出的k可能比链表总长度长因此要进行取模操作,当k=0的时候可以直接返回以免在操作的时候产生环。


public ListNode rotateRight(ListNode head, int n) {
        if(head == null || head.next == null || n == 0) {
            return head;
        }
        int cnt = 0;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        
        ListNode temp = head;
        while(temp != null) {
            cnt++; temp = temp.next;
        }
        n = n % cnt; 
        if(n == 0) return head; // return here for safe
        ListNode temp1 = head;
        while(n > 1) {
            temp1 = temp1.next; n--;
        }
        temp = dummy; ListNode temp2 = head;
        while(temp1.next != null) { // we need the tail to relink the list
            temp1 = temp1.next;
            temp2 = temp2.next;
            temp = temp.next;
        }
        temp1.next = dummy.next;
        dummy.next = temp2;
        temp.next = null;
        
        return dummy.next;
    }

没有评论:

发表评论