zoukankan      html  css  js  c++  java
  • 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是原来链表的头结点,不是逆转后的头结点了。
        }
    };
  • 相关阅读:
    常用的服务器简介
    PHP Proxy 负载均衡技术
    Hexo 博客Next 搭建与美化主题
    Tomcat PUT方法任意文件上传(CVE-2017-12615)
    哈希爆破神器Hashcat的用法
    内网转发随想
    Oauth2.0认证
    Github搜索语法
    记一次挖矿木马清除过程
    利用ICMP进行命令控制和隧道传输
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3708930.html
Copyright © 2011-2022 走看看