zoukankan      html  css  js  c++  java
  • [LeetCode]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.

    解题思路:

    注意k会大于链表长度: k % length.

     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 (!head || k == 0) return head;
    13         
    14         int length = 1;
    15         ListNode *cur = head;
    16         for (; cur->next != nullptr ; cur = cur->next) {
    17             ++length;
    18         }
    19         k = length - k % length;
    20         
    21         cur->next = head;
    22         for (int i =0; i < k; i++) {
    23             cur = cur->next;
    24         }
    25         
    26         head = cur->next;
    27         cur->next = nullptr;
    28         
    29         return head;
    30     }
    31 };
  • 相关阅读:
    弗尤博客(二)
    弗尤博客(一)
    第一系列完
    C# 关闭子窗体释放子窗体对象问题
    C#设置IE代理
    C# 计算位置居中
    C# 绘图
    From传值
    pictureBox绑定Base64字符串
    C# 绘制圆角矩形
  • 原文地址:https://www.cnblogs.com/skycore/p/4916003.html
Copyright © 2011-2022 走看看