題目: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
.
解題思路:題意為給定一個鏈表,要求按照給定的位置進行反轉。示例代碼如下:
public class Solution { public ListNode rotateRight(ListNode head, int k) { if (head == null) return null; ListNode p = head; ListNode q = head; int num = 1;//統計鏈表元素個數 while (p.next != null) { num++; p = p.next;//p指向尾節點 } int n = 1; if (k >= num) k = k % num;//處理循環反轉的情況 while (n < num - k) { n++; q = q.next; } ListNode h = null; if (q.next != null) { //將q後面的節點作為新的頭結點 h = q.next; q.next = null; p.next = head; } else { h = head; } return h; } }