zoukankan      html  css  js  c++  java
  • [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;
        }
    };
    

      

  • 相关阅读:
    iOS 设计模式-委托模式
    python中时间操作总结
    list、dict、tuple的一些小操作总结
    DataFrame的构建及一些操作
    python连接mysql、oracle小例子
    sqlalchemy 映射的小例子
    crontab定时任务以及其中中文乱码问题
    vs2008试用版的评估期已经结束解决办法
    MongoDB 常用shell命令汇总
    把py文件打成exe
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3442370.html
Copyright © 2011-2022 走看看