LeetCode | Rotate List

2014-11-24 10:52:36 · 作者: · 浏览: 0

题目

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.

分析

先得到链表长度len,n对len取余就是需要右转长度(也可以不要长度,就是指针移动n次找到剪切位置,但是如果n过大就悲剧了),然后找到剪切位置,这里依然用个哨兵简化代码。

代码

public class RotateList {
	public ListNode rotateRight(ListNode head, int n) {
		if (head == null || n == 0) {
			return head;
		}
		ListNode tail = head;
		int len = 1;
		while (tail.next != null) {
			tail = tail.next;
			++len;
		}
		n = len - n % len;
		if (n == len) {
			return head;
		}
		ListNode dummy = new ListNode(0);
		dummy.next = head;
		head = dummy;
		for (int i = 0; i < n; ++i) {
			head = head.next;
		}
		tail.next = dummy.next;
		dummy.next = head.next;
		head.next = null;
		return dummy.next;
	}
}