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

  • 相关阅读:
    Windows Server 2012 R2搭键域环境
    JS节点的属性: nodeType, nodeName, nodeValue
    JS获取文本节点
    JS获取元素节点的子节点
    读写属性节点
    获取指定的元素节点
    JAVA学习--反射之动态代理模式
    JAVA学习--反射之静态代理模式
    JAVA学习--反射其他操作
    JAVA学习--反射构造器操作
  • 原文地址:https://www.cnblogs.com/higerzhang/p/4037651.html
Copyright © 2011-2022 走看看