• [LeetCode]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

    思考:翻转部分链表。

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
    	void ReverseList(ListNode *&begin,ListNode *&end)
    	{
    		ListNode *p=begin;
    		ListNode *q=p->next;
    		while(q)
    		{
    			if(q==end) q->next=NULL;
    			p->next=q->next;
    			q->next=begin;
    			begin=q;
    			q=p->next;
    		}
    		end=p;
    	}
        ListNode *reverseKGroup(ListNode *head, int k) {
            // IMPORTANT: Please reset any member data you declared, as
            // the same Solution instance will be reused for each test case.
    		if(head==NULL||k==1) return head;
    		ListNode *p=head;
    		int sum=0;
    		while(p)
    		{
    			sum++;
    			p=p->next;
    		}
    		if(sum<k) return head;
    		p=head;
    		ListNode *begin,*end;
    		ListNode *newhead=NULL;
    		ListNode *r,*last;
    		while(sum>=k)
    		{
    			ListNode *q=p;
    			for(int i=0;i<k-1;i++)
    			{
    				q=q->next;
    			}
    			begin=p;end=q;r=q->next;
    			ReverseList(begin,end);
    			if(newhead==NULL)
    			{
    				newhead=begin;
    				end->next=r;
    				last=end;
    			}
    			else 
    			{
    				last->next=begin;
    				last=end;
    			}
    			p=r;
    			sum-=k;
    		}	
    		if(p) last->next=p;
    		return newhead;
        }
    };
    

      

  • 相关阅读:
    分布式系统学习一-概念篇
    JAVA多线程学习九-原子性操作类的应用
    JAVA多线程学习八-多个线程之间共享数据的方式
    JAVA多线程学习七-线程池
    vue 工作随笔
    智能云课堂整理
    mysql
    模板引挚 jade ejs
    node实战小例子
    昭山欢node资料学习笔记
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3442370.html
Copyright © 2020-2023  润新知