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

      

  • 相关阅读:
    属性,选择器和css
    笔记
    浏览器
    单位
    marquee 滚动标签
    双飞翼布局与圣杯布局
    随便看看吧
    光标的形状 颜色的表示方法
    如何实现浏览器title中的小图标
    解决浏览器兼容问题 补充
  • 原文地址:https://www.cnblogs.com/Rosanna/p/3442370.html
Copyright © 2011-2022 走看看