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

  

posted @ 2013-11-25 22:29  七年之后  阅读(182)  评论(0编辑  收藏  举报