zoukankan      html  css  js  c++  java
  • 61. Rotate List

    • Total Accepted: 96273
    • Total Submissions: 399212
    • Difficulty: Medium
    • Contributors: Admin

    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.

    分析


    这里题目的 test case 有一个没有说清楚的条件,就是当 k > list.size ,怎么处理, 实际上题目是取模的 
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        /**
         *              p     t
         * dummy->1->2->3->4->5->NULL , k = 2
         */
        ListNode* rotateRight(ListNode* head, int k) {
            if(k == 0 || head == NULL) return head;
            int len = 0;
            ListNode dummy(0);
            ListNode* tail = head;
            ListNode* pos = &dummy;
            dummy.next = head;
             
            while(tail != NULL){
                tail = tail->next;
                ++len;
            }
            k = k % len;
            if(k == 0) return head;
             
            tail = head;
            while(--k){
                tail = tail->next;
            }
            while(tail->next != NULL){
                pos = pos->next;
                tail = tail->next;
            }
            tail->next = dummy.next;
            head = pos->next;
            pos->next = NULL;
             
            return head;
             
        }
    };




  • 相关阅读:
    MySQL主从复制的作用?
    MySQL的逻辑架构
    SQL语句的执行流程
    Count(*)在不同引擎的实现方式
    视图
    MySQL经典练习题(五)
    pyinstaller基本操作
    git基本操作
    Ubuntu安装tensorflow
    ScrollView can host only one direct child
  • 原文地址:https://www.cnblogs.com/zhxshseu/p/fb42117c3f96b1fb60a6e4a54dda6b33.html
Copyright © 2011-2022 走看看