zoukankan      html  css  js  c++  java
  • 【Leetcode】【Medium】Rotate List

    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.

    解题思路:

    题目看上去很简单,但是需要注意一下点:

    1、任何输入都有可能,即使是无效的输入(例如链表为空,k不为0),所以程序开始时的检查在任何时候都非常重要。

    2、另一个边界条件,就是是否在空指针中,使用了->next操作,很多链表错误都发生在此处。

    3、K是旋转的结点数,因此K可能大于整个链表的结点数。

    4、K不仅可能大于结点数,还可能非常大,因此传统的循环耗费时间太多,要对K做取余操作。

    代码:

     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         if (k == 0 || !head)
    13             return head;
    14         ListNode* pre = head;
    15         ListNode* last = head;
    16         int num = 1;
    17         while (k--) {
    18             if (last->next) {
    19                 num++;
    20                 last = last->next;
    21             } else {
    22                 k = k % num;
    23                 last = head;
    24             }
    25         }
    26         
    27         while (last->next) {
    28             pre = pre->next;
    29             last = last->next;
    30         }
    31         
    32         last->next = head;
    33         head = pre->next;
    34         pre->next = NULL;
    35         return head;
    36     }
    37 }
  • 相关阅读:
    《Java多线程编程核心技术》——多线程与同步
    《垃圾回收的算法与实现》——Python垃圾回收
    命令提示符
    clip
    explorer
    dotnet 命令启动报错
    Superfetch/SysMain
    Windows
    Windows 系统授权服务信息
    Windows 命令
  • 原文地址:https://www.cnblogs.com/huxiao-tee/p/4513491.html
Copyright © 2011-2022 走看看