首页 > 其他 > 详细

61. Rotate List

时间:2019-10-08 21:57:49      阅读:84      评论:0      收藏:0      [点我收藏+]

题目描述

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了,断开就好。

61. Rotate List

原文:https://www.cnblogs.com/kykai/p/11637719.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!