zoukankan      html  css  js  c++  java
  • leetcode第24题--Reverse Nodes in k-Group

    problem:

    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

    就是上一题的一般形式。上题的k是2.这里的k是任意的整数。

    子函数先将一个链表反转,然后在主函数里调用。链表的反转基本上四个语句就搞定了,自己想死也想不出来啊。不过算是学习了。以后碰到类似的应该要会利用。参考了一位java的代码。这里我改成了C++的代码。java的主页在http://www.cnblogs.com/lichen782/p/leetcode_Reverse_Nodes_in_kGroup.html。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    private:
    ListNode *reverseList(ListNode *pre, ListNode *tail) // tail 为第 k+1
    {
        ListNode *last = pre -> next;
        ListNode *cur = last -> next;
        while(cur != tail)
        {
            last->next = cur -> next;
            cur -> next = pre -> next;
            pre -> next = cur;
            cur = last -> next;
        }
        return last; // 这个last为第k,也就是每组的最后一个,作为下一组的头
    }
    public:
    ListNode *reverseKGroup(ListNode *head, int k)
    {
        int i = 0;
        ListNode *dummy = new ListNode(0);
        ListNode *pre = dummy;
        dummy -> next = head;
        while(head)
        {
            i++;
            if(i % k == 0)
            {
                pre = reverseList(pre, head -> next); // 此时head指向第k个,就是每组的最后一个,所以尾应该是head的next
                head = pre -> next; // head应该是前一组的最后一个的下一个
            }
            else
                head = head -> next;
        }
        return dummy -> next;
    }
    };

    本例主要学习如何反转一个list

  • 相关阅读:
    easyui-lang-zh_CN.js导入后还是英文提示
    MongoDB的备份(mongodump)与恢复(mongorestore)
    mongodb windows下服务安装与卸载
    MongoDB 权限管理 用户名和密码的操作
    Super Hide IP 3.4.7.8允许您以匿名方式进行网上冲浪、 保持隐藏您的 IP 地址
    Delphi IDE下载全地址
    Delphi IDE下载全地址
    Delphi XE2及以后的版本编译后的程序大小问题
    Delphi XE2及以后的版本编译后的程序大小问题
    DevExpress VCL 一键安装工具
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4037651.html
Copyright © 2011-2022 走看看