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

  • 相关阅读:
    最大子序列和问题之算法优化
    数据揭秘:低学历成功逆袭概率有多少?感谢父母送我读书!
    据说这份高考卷,只有程序员能得满分!
    牛客OI赛制测试赛2
    斯特林公式
    N!的近似值_斯特林公式
    矩阵快速幂
    回文树
    回文树入门
    环和链的判断
  • 原文地址:https://www.cnblogs.com/kykai/p/11637719.html
Copyright © 2020-2023  润新知