• LeetCode25 Reverse Nodes in k-Group


    题意:

    Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

    If the number of nodes is not a multiple of k then left-out nodes in the end should remain as it is.

    You may not alter the values in the nodes, only nodes itself may be changed.

    Only constant memory is allowed.

    For example,
    Given this linked list: 1->2->3->4->5

    For k = 2, you should return: 2->1->4->3->5

    For k = 3, you should return: 3->2->1->4->5 (Hard)

    分析:

    题目意思是每k个链表进行翻转,不足k个保持不变。

    可以写一个翻转k个节点的辅助函数,然后在原函数中判断后续是否有k个节点,以及后续节点位置。

    注意事项见代码注释。

    代码:

     1 class Solution {
     2 private:
     3     ListNode* reverseKelement(ListNode* head, int k) {
     4         ListNode* result = nullptr;
     5         for (int i = 0; i < k; ++i) {
     6             ListNode* temp = head -> next;
     7             head -> next = result;
     8             result = head;
     9             head = temp;
    10         }
    11         return result;
    12     }
    13 public:
    14     ListNode* reverseKGroup(ListNode* head, int k) {
    15         if (head == nullptr) {
    16             return head;
    17         }
    18         ListNode dummy(0);
    19         dummy.next = head;
    20         head = &dummy;
    21         
    22         ListNode* runner = head -> next;
    23         int flag = 1;
    24         for (int i = 0; i < k; ++i) {
    25             if (runner -> next != nullptr || (runner -> next == nullptr && k == i + 1) ) { //恰好k个到结尾情况没考虑, 例如[1,2] 2情况
    26                 runner = runner -> next;
    27             }
    28             else {
    29                 flag = 0;
    30                 break;
    31             }
    32         }
    33         while (flag == 1) {
    34             ListNode* temp1 = head -> next;
    35             head -> next = reverseKelement(temp1, k);
    36             temp1 -> next = runner;
    37             head = temp1;
    38             for (int i = 0; i < k; ++i) {
    39                 if (runner != nullptr && (runner -> next != nullptr || (runner -> next == nullptr && k == i + 1)) ) { //对应添加runner !=  nullptr
    40                     runner = runner -> next;
    41                 }
    42                 else {
    43                     flag = 0;
    44                     break;
    45                 }
    46             }
    47         }
    48         return dummy.next;
    49     }
    50 };
     
  • 相关阅读:
    php array function
    scrum敏捷开发重点介绍
    PHP文件操作
    正则
    PHP面向对象
    PHP数组
    PHP函数参数
    PHP运算符优先级
    PHP判断变量类型和类型转换的三种方式
    PHP变量的传值和引用
  • 原文地址:https://www.cnblogs.com/wangxiaobao/p/5774082.html
Copyright © 2020-2023  润新知