leetcode -- 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个数,结果发现k可能会比len大,到网上搜索了下:
从head节点开始跑,一直跑到尾节点,得到len,将尾节点的next指针指向head,接着跑(len -n) % len步,断开
这里需注意(len -n) % len可能为负数,需+len
1 /** 2 * Definition for singly-linked list. 3 * public class ListNode { 4 * int val; 5 * ListNode next; 6 * ListNode(int x) { 7 * val = x; 8 * next = null; 9 * } 10 * } 11 */ 12 public class Solution { 13 public ListNode rotateRight(ListNode head, int n) { 14 // Start typing your Java solution below 15 // DO NOT write main() function 16 if(head == null || n == 0){ 17 return head; 18 } 19 int len = 1; 20 ListNode p = head; 21 while(p.next != null){ 22 len ++; 23 p = p.next; 24 } 25 p.next = head; 26 /* 27 int count = (len - n - 1) % len; 28 while(count < 0){ 29 count += len; 30 count %= len; 31 } 32 p = head; 33 */ 34 int count = (len - n) % len; 35 while(count < 0){ 36 count += len; 37 count %= len; 38 } 39 int step = 0; 40 while(step < count){ 41 p = p.next; 42 step ++; 43 } 44 head = p.next; 45 p.next = null; 46 return head; 47 } 48 }