6/08/2014

111. Rotate List

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode rotateRight(ListNode head, int n) {
        if (head==null) return null;
       
        ListNode front = head;
        ListNode back = head;
        ListNode end = head;
       
        while (front.next!=null) front = front.next;
       
        end = front;
        front.next = head;
        front = head;
       
        for (int i=0; i<n; i++) {
            front = front.next;
        }
       
        while (front!=end) {
            front = front.next;
            back = back.next;
        }
       
        ListNode rotateHead = back.next;
        back.next = null;
       
        return rotateHead;
    }
}

没有评论:

发表评论