您的位置:首页 > Web前端 > Node.js

LeetCode 25: Reverse Nodes in k-Group

2015-06-08 20:00 567 查看
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


题目要求对链表中的元素按K个一组,反序后,形成新的链表。对于最后不满K个元素,保持原来的顺序输出。所以本题可以按如下方法解:


1、建立空的新链表list1.


2、如果原链表剩余元素个数不小于K个,则取K个元素,采用头插法构建反序的临时链表,插入list1的尾部。


3、如果链表剩余元素个数小于K个,则将剩余的链表插入到list1的尾部。


代码如下:


//计算链表长度
	int getListSize(ListNode* head)
	{
		int count = 0;
		while (head)
		{
			head = head->next;
			count++;
		}
		return count;
	}
	//在链表头部插入元素,返回插入后的链表头指针
	ListNode* addHead(ListNode*head, ListNode*Node)
	{
		Node->next = head;
		return Node;
	}
	ListNode* reverseKGroup(ListNode* head, int k) {
		int length = getListSize(head);
		ListNode tmpHead(-1);
		ListNode *pNode = &tmpHead;
		while(length >= k){
			ListNode* pHead = NULL;
			for (int i=0; i<k; i++)
			{
				ListNode*ptmpNode = head;
				head = head->next;
				ptmpNode->next = NULL;
				//透过头插法构建反序的临时链表
				pHead = addHead(pHead, ptmpNode);
			}
			pNode->next = pHead;
			while(pNode->next)
				pNode = pNode->next;
			length -= k;
		}
		//将链表剩余元素插入结果链表的尾部
		pNode->next = head;
		return tmpHead.next;
	}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: