zoukankan      html  css  js  c++  java
  • [Leetcode 57] 61 Rotate List

    Problem:

    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.

    Analysis:

    The first thought is to use the same strategy as in "Remove Kth Node in List" -- using two pointers, one is kth precedeeding the other. And once the former point to the null, the latter points to the place we need to set as new head. It seems this doesn't work in many cases.

    Then the other solution is to first make the given list as a circle. And then go to the desired position to break the circle form a new list.

    Code:

     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         // Start typing your C/C++ solution below
    13         // DO NOT write int main() function
    14         if (head == NULL) return head;
    15         
    16         int cnt = 1;
    17         ListNode *tmp = head;
    18         while (tmp->next != NULL) {
    19             tmp = tmp->next;
    20             cnt++;
    21         }
    22         
    23         tmp->next = head;
    24         tmp = head;
    25         int pos = cnt -  k % cnt;
    26         while (--pos) {
    27             tmp = tmp->next;
    28         }
    29         head = tmp->next;
    30         tmp->next = NULL;
    31         
    32         return head;
    33     }
    34 };
    View Code
  • 相关阅读:
    [BZOJ1415]聪聪和可可
    [POJ2096]Collecting Bugs
    开博第一天
    实现CSS样式垂直水平完全居中
    Vue中独立组件之间数据交互
    python Template中substitute()的使用
    eclipse 编辑 python 中文乱码的解决方案
    java Math.random()随机数的产生
    java文件读写的两种方式
    My way on Linux
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099812.html
Copyright © 2011-2022 走看看