zoukankan      html  css  js  c++  java
  • 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了,断开就好。

  • 相关阅读:
    软件开发规范
    Fail2ban + firewalld 防护doss攻击
    SourceTree&Git部分名词解释
    训子
    一个网络下,手机如何访问本地网址
    tempalte.js的一般用法
    template.js的介绍
    获取URL中的参数
    js判断苹果和安卓端或者wp端
    HTML5与WebGL编程
  • 原文地址:https://www.cnblogs.com/kykai/p/11637719.html
Copyright © 2011-2022 走看看