[LeetCode OJ 061] Rotate List
Question: Given a list, rotate the list to the right bykplaces, wherekis non-negative.
For example:
Given1-> 2-> 3-> 4-> 5-> NULL
Andk =2
,
Return4-> 5-> 1-> 2-> 3-> NULL
.
Solution: A linked list must be reversed Based on the given position. The sample code is as follows:
Public class Solution {public ListNode rotateRight (ListNode head, int k) {if (head = null) return null; ListNode p = head; ListNode q = head; int num = 1; // count the number of elements in the linked list while (p. next! = Null) {num ++; p = p. next; // p points to the End Node} int n = 1; if (k> = num) k = k % num; // process the loop reversal condition while (n <num-k) {n ++; q = q. next;} ListNode h = null; if (q. next! = Null) {// use the node after q as the new header node h = q. next; q. next = null; p. next = head;} else {h = head;} return h ;}}