• [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
  • 相关阅读:
    ASP创建对象及中文显示解决方法
    webservice解读
    top监控工具
    Crontab实例
    javascript闭包的理解
    98万买下51.com域名,51.com不止2000万美金
    百度08年网页搜索份额73.2% 创历史新高
    讲故事投资 天使投资人的中国式生存
    下个谷歌将诞生于中国或印度
    Twitter入选10大搜索引擎
  • 原文地址:https://www.cnblogs.com/freeneng/p/3099812.html
Copyright © 2020-2023  润新知