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

  • 相关阅读:
    手把手教NIS Edit安装向导的使用
    使用HM NIS Edit制作软件安装包
    有哪些适合学习英语的纪录片 ?
    Android入门(一)AndroidStudio下的APP目录结构介绍
    架构和框架的区别
    Git版本控制的快捷方式(GITCHEAT SHEET)
    DOS下启动MySQL时输入net start mysql 提示服务名无效的问题
    个人搜查小问题
    oozie说明(本文参考多处,自己留看)
    oozie fork join结点
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4037651.html
Copyright © 2011-2022 走看看