Rotate List ,反转链表的右k个元素

问题描述:

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取模。

public ListNode rotateRight(ListNode head, int k) {
		int lenth = 0;//链表长度
		ListNode headd = head;
		while (headd != null) {
			lenth++;
			headd = headd.next;
		}
		if (head == null || head.next == null || k % lenth == 0) {
			return head;
		}

		ListNode headc = head;
		for (int i = 1; i < lenth - k % lenth; i++) {
			headc = headc.next;
		}
		ListNode newHead = headc.next;
		ListNode p = newHead;
		while (p.next != null) {
			p = p.next;
		}
		p.next = head;
		headc.next = null;

		return newHead;
	}
原文地址:https://www.cnblogs.com/masterlibin/p/5753391.html