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

  • 相关阅读:
    JQuery:JQuery语法、选择器、事件处理
    循序渐进DB2(第2版)——DBA系统管理、运维与应用案例
    高级进阶DB2(第2版)——内部结构、高级管理与问题诊断
    DB2数据库性能调整和优化(第2版)
    金融工程中的蒙特卡罗方法
    代数学教程
    拓扑线性空间与算子谱理论
    李代数(第2版)
    编程的修炼(中英双语)
    iOS应用开发详解
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4037651.html
Copyright © 2011-2022 走看看