zoukankan      html  css  js  c++  java
  • 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.

    分析:首先遍历list得到长度,然后找到应该rotate的位置,进行rotate。注意:k有可能大于长度,因此要进行取模运算。

    运行时间:12ms

     1 /**
     2  * Definition for singly-linked list.
     3  * struct ListNode {
     4  *     int val;
     5  *     ListNode *next;
     6  *     ListNode(int x) : val(x), next(NULL) {}
     7  * };
     8  */
     9 class Solution {
    10 public:
    11     ListNode* rotateRight(ListNode* head, int k) {
    12         if(!head || !head->next) return head;
    13         if(k == 0) return head;
    14         
    15         int len = 0;
    16         ListNode* move = head;
    17         while(move->next){ // find the end of the list
    18             len++;
    19             move = move->next;
    20         }
    21         ListNode* end = move;
    22         len++; // length of the list
    23         
    24         int count = 0;
    25         move->next = head;
    26         while(count < len - k % len){ // find the position of the rotating node
    27             count++;
    28             move = move->next;  // move is the position of the node before the rotating node
    29         }
    30         ListNode* rotate = move->next; // rotate is the position of the rotating node
    31         
    32         end->next = head;
    33         move->next = NULL;
    34         return rotate;
    35     }
    36 };
  • 相关阅读:
    面试题整理
    Node.js核心模块-stream流
    Node.js核心模块-crypto加密
    Node.js核心模块-assert
    Node.js全局对象-process
    nodemon
    随笔
    python学习笔记(十四): unittest
    python学习笔记(十三): 多线程多进程
    python学习笔记(十二):发送邮件
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4512809.html
Copyright © 2011-2022 走看看