【Leetcode】Rotate List

题目链接:https://leetcode.com/problems/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的边界情况

算法:

	public ListNode rotateRight(ListNode head, int k) {
		ListNode p = head, rear = head;
		int length = 0;
		while (p != null) {// 计算表长
			length++;
			if (p.next == null) {
				rear = p;// rear指向表尾
			}
			p = p.next;
		}
		if (head == null || length == 0) {
			return head;
		}
		if (k > length) {
			k = k % length;
		}
		if (k == 0 || k == length) {
			return head;
		}

		p = head;
		int rotateIndex = length - k;
		while (--rotateIndex > 0) {
			p = p.next;
		} // 此时p指向倒数k+1一个位置

		rear.next = head;
		head = p.next;
		p.next = null;
		return head;
	}


你可能感兴趣的:(【Leetcode】Rotate List)