61. Rotate List

题目描述

Given a linked list, rotate the list to the right by k places, where k is non-negative.

Example 1:

Input: 1->2->3->4->5->NULL, k = 2
Output: 4->5->1->2->3->NULL

Example 2:

Input: 0->1->2->NULL, k = 4
Output: 2->0->1->NULL

参考答案

 1 class Solution {
 2 public:
 3     ListNode* rotateRight(ListNode* head, int k) {
 4         if(!head) return 0;
 5         ListNode * cur;
 6         ListNode * nHead;
 7         cur = nHead = head;
 8         int len = 1;
 9         
10         while(cur->next){
11             cur = cur->next;
12             len++;
13         }
14         cur ->next  = head;
15         
16         if(k%=len){
17             for(int i = 0 ; i<len-k;i++){
18                 cur = cur->next;
19             }
20         }
21         nHead = cur->next;
22         cur->next = NULL;
23         return nHead;
24         
25     }
26 };

答案分析

分成三部分:

1. 链接首尾

2. 移动

3. 拆开

第一部分,连接首位。建立cur,进行loop,得到cur->next,然后将head续给next,同时并记录list的个数。

第二部分,移动。因为是从尾巴向前移动,因此,在算完 k%len 后,还需要 k = len - k % len。 

第三部分,断开。由于 cur 是 head 的前,因此需要head = cur->next,然后就不需要cur->next了,断开就好。

posted @ 2019-10-08 20:23  schaffen  阅读(153)  评论(0编辑  收藏  举报