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 };
  • 相关阅读:
    Java Native Method
    SQL语句优化
    Ibatis的环境搭建以及遇到的问题解决
    Java 构建器
    SpringMVC自定义视图 Excel视图和PDF视图
    java 枚举的常见使用方法
    mysql 根据某些字段之和排序
    MFC The Screen Flickers When The Image Zoomed
    How To Debug Qmake Pro File
    Gcc And MakeFile Level1
  • 原文地址:https://www.cnblogs.com/amazingzoe/p/4512809.html
Copyright © 2011-2022 走看看