2015年6月2日星期二

Rotate List leetcode

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对length取莫. 用快慢指针方法 快指针先走k步 然后一起走.
 最后快指针停在最后面的位置 (null之前),慢指针停在要翻转的前一个位置.
记录slow.next就是newhead结点, fast,next 指向原来的head, slow.next指向null

public class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if (k == 0 || head == null) {
            return head;
        }
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode fast = head;
        ListNode slow = head;
        ListNode cur = head;
        int len = 0;
        while (cur != null) {
            cur = cur.next;
            len++;
        }
        k = k%len;
        for (int i = 0; i < k; i++) {
            fast = fast.next;
        }
        while (fast.next != null) {
            fast = fast.next;
            slow = slow.next;
        }
        fast.next = head;
        dummy.next = slow.next;
        slow.next = null;
        return dummy.next;
    }
    
}

没有评论:

发表评论