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;
        }
    };
    

      

  • 相关阅读:
    .NET Page对象各事件执行顺序
    允许webservice远程在ie里面调用配置方法
    sea.js模块化编程
    atom配置web开发环境
    CSS代码规范
    HTML DOM总结
    10分钟写一个markdown编辑器
    sea.js详解
    圣杯布局 双飞翼布局
    Spring学习(1)
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3442370.html
Copyright © 2011-2022 走看看