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 };
  • 相关阅读:
    发现WPF在Windows 7 的一个BUG ,多点触摸开发的注意了
    广度优先搜索 与 深度优先算法
    log4net window UAC下无法记录解决
    简单网页制作
    JS常用属性
    JS for循环、if判断、white循环。
    mysql 查询
    HTML学习随笔
    JS小练习
    mysql增删改
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4512809.html
Copyright © 2011-2022 走看看