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是原来链表的头结点,不是逆转后的头结点了。
        }
    };
  • 相关阅读:
    [offer_53-1] 在排序数组中查找数字 I (开启编辑看 i,j,m)
    window10 办公软件word、execel、ppt突然变得很卡顿如何解决?
    数组中第k大的数
    heapq 堆
    每日一题 482. 密钥格式化
    算法笔记Go!
    DFS与BFS的python实现
    无向图中找到长度为k的“链”
    无序数组中找一个比左边都大、右边都小的数
    SRM(空域富模型隐写分析)
  • 原文地址:https://www.cnblogs.com/awy-blog/p/3708930.html
Copyright © 2011-2022 走看看