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
  • 相关阅读:
    mysql时区设置
    jquery raidio buttion checked unchecked
    mysql定时备份
    丁香园 (http://www.dxy.cn)这个名字听着
    mysql backup solution
    mysql备份
    mysql编码设置
    在Ubuntu中通过源码安装编译安装软件(MySQL篇) 收藏
    社会化分享实现插件,分享到...
    ubuntu 小工具
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099812.html
Copyright © 2011-2022 走看看