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
  • 相关阅读:
    hdu 3333 树状数组+离线处理
    poj 2352 树状数组 OR Treap
    hdu 1698 线段树
    【概率dp】D. Card Collector
    【分段哈希】H. Paint the Wall
    【置换】G. Poker 2.0
    【概率dp】C. Race to 1 Again
    【dp】D. Caesar's Legions
    【并查集】F.find the most comfortable road
    【算法系列学习】连续邮资问题
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099812.html
Copyright © 2011-2022 走看看