Friday, August 1, 2014

[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.

解题思路: 因为n可能会大于list的总长度,所以我们先遍历整个list,然后将tail指向head,组成一个圈,然后再走num - n%num步,就将圈解开即可。
最开始自己是一遍一遍的遍历list。看了水中的鱼的讲解,觉得很赞。

Java Code:


public ListNode rotateRight(ListNode head, int n) {
        if(head == null || n == 0) return head;
        
        ListNode p = head;
        
        int count = 1;
        while(p.next != null){
             count++;
             p = p.next;
        }
        
        if(n%count == 0) return head;
        
       p.next = head;
       int i = 0;
        
       while( i < count - n%count){
           i++;
           p = p.next;
       }
       
       ListNode newhead = p.next;
       p.next = null;
       
       return newhead;
    }

No comments:

Post a Comment