• 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

    思路:将前k个结点完全逆转。主要就是一个swap链表节点的升级版本,将前k个结点完全逆转,而不是两个结点的逆转。首先我们定义一个逆序链表函数,然后在进行遍历到k,然后调用逆序链表函数,前k个结点都要访问2次,故时间复杂度为O(2*n)=O(n).

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *reverse(ListNode *beg,ListNode *end)
        {
            if(beg==NULL)
                return beg;
            ListNode *head=beg;
            ListNode *pCur=beg->next;
            while(pCur!=NULL)
            {
                ListNode *pNext=pCur->next;
                pCur->next=beg;
                beg=pCur;
                pCur=pNext;
            }
            end->next=beg;   //注意这里,并不是代表末尾函数
            return head;
        }
        ListNode *reverseKGroup(ListNode *head, int k) {
            if(head==NULL||k<=1)
                return head;
            ListNode *pHead=new ListNode(0);
            pHead->next=head;
            ListNode *pPre=pHead;
            ListNode *pCur=head;
            int count=0;
            while(pCur!=NULL)
            {
                count++;
                ListNode *pNext=pCur->next;
                if(count==k)
                {
                    pCur->next=NULL;  //这里要是pCur->next指向NULL,为reverse函数终止做准备
                    pPre=reverse(pPre->next,pPre);
                    pPre->next=pNext;           //返回逆转后的末尾结点(原来的头结点)要指向k+1结点
                    count=0;
                }
                pCur=pNext;
            }
            return pHead->next;//注意这里不能返回head,因为head是原来链表的头结点,不是逆转后的头结点了。
        }
    };
  • 相关阅读:
    ros论坛
    python--dict和set类型--4
    python--条件判断和循环--3
    python--list和tuple类型--2
    Unicode与UTF-8互转(C语言实现)
    spring mvc 返回JSON数据
    值得学习的C语言开源项目和库
    mudos源码分析
    Freemarker使用总结
    Maven详解
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3708930.html
Copyright © 2020-2023  润新知