zoukankan      html  css  js  c++  java
  • [LeetCode] 61. 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 个元素至列表最前面。

    关键是找到最后元素 lastOne 和 旋转后列表新的最后元素 newLastOne

     1     ListNode* rotateRight(ListNode* head, int k) {
     2     
     3         if (head == NULL) {
     4             return NULL;
     5         }
     6         
     7         int n = 1;
     8         ListNode* lastOne = head;
     9         while (lastOne->next != NULL) {
    10             n++;
    11             lastOne = lastOne->next;
    12         }
    13         
    14         if (n == k) {
    15             return head;
    16         }
    17         
    18       int firstNum = n - (k % n);
    19                 
    20         ListNode* newLastOne;
    21         newLastOne = head;
    22         for (int i = 1; i < firstNum; i++) {
    23             newLastOne = newLastOne->next;
    24         }
    25                 
    26         lastOne->next = head;
    27         head = newLastOne->next;
    28         newLastOne->next = NULL;
    29         
    30         return head;
    31     }
  • 相关阅读:
    Spring中的AOP
    P2782 友好城市
    1576 最长严格上升子序列
    1058 合唱队形 2004年NOIP全国联赛提高组
    5294 挖地雷
    1643 线段覆盖 3
    4768 跳石头
    1026 逃跑的拉尔夫
    2727:仙岛求药
    codevs 4888 零件分组
  • 原文地址:https://www.cnblogs.com/TonyYPZhang/p/5068620.html
Copyright © 2011-2022 走看看