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

    又是一道链表的题,关于链表的题好像都是关于指针的,题目都不难吧,主要是需要细心,因为不难,所以代码没有自己写,这里还可以考虑之前做过的链表翻转m至n那道题,然后调用函数就解决了······················

    下面的代码的思路是用子函数挨个处理每个K段。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* reverse(ListNode* head){
            ListNode* prev = nullptr;
            ListNode* nowNode = head;
            while(nowNode){
                ListNode* next = nowNode -> next;
                nowNode -> next =  prev;
                prev = nowNode;
                nowNode = next;
            }
            return prev;
        }
        ListNode *reverseKGroup(ListNode *head, int k) {
            if(head == nullptr || head -> next == nullptr || k < 2) return head;
            
            int cnt = 1;
            ListNode* nowHead = head;
            ListNode* nowNode = head;
            while(nowNode && cnt < k){
                cnt ++;
                nowNode = nowNode -> next;
            }
            if(nowNode && cnt == k){
                ListNode* tail = reverseKGroup(nowNode -> next , k);
                nowNode -> next = nullptr;
                head = reverse(head);
                nowHead -> next = tail;
            }
            return head;
        }
    };

      

  • 相关阅读:
    js处理富文本编辑器转义、去除转义、去除HTML标签
    web sec tools / Arachni
    OS + Linux IP / Inside IP / Outside IP
    OS + Linux SMB / Samba
    OS + Linux NTP Server
    my live / PC NAS / weiliantong QNAP TS-532X 4.5.1.1495 / cipanzhenlie / raid / Synology
    summarise() regrouping output 警告
    binary_crossentropy和BinaryCrossentropy的区别
    损失函数BinaryCrossentropy例子说明
    理解功能强大的sed替换命令
  • 原文地址:https://www.cnblogs.com/qiaozhoulin/p/4775903.html
Copyright © 2011-2022 走看看