leetcode025: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

問題分析

以k個結點爲一組,逆轉組內結點後連接起來,是leetcode024的升級版本(k=2)。解題思路比較清晰,先查看是否有足夠的結點構成一組,有則逆轉,不夠則直接連接起來。難點是鏈表操作的先後複製要清晰,否則容易混亂。下面以鏈表爲12345678,k=3爲例說明鏈表複製的過程(鏈表逆轉邏輯比較簡單,這裏不提)。
  • ans是最終結果的表頭指針;
  • ans_p是負責組間連接工作的結點指針;
  • p是負責檢查是否還有k個結點需要逆轉的結點指針;
  • p1用來記錄逆轉前的組的表頭指針;
  • q爲逆轉過程中的表頭指針。


代碼

<pre name="code" class="cpp">//運行時間:38ms
class Solution {
public:
	ListNode *reverseKGroup(ListNode *head, int k) {
		if (!head) return NULL;
		if (k<=1) return head;
		ListNode *ans = NULL;
		ListNode *ans_p = head;
		ListNode *p = head;//前進!
		ListNode *p1;
		ListNode *q = head;
		ListNode *x;
		ListNode *y;
		int count ;
		while (1){
			count = 0;
			p1 = p;
			while (p&&count < k){
				count++;
				p = p->next;
			}
			if (count < k) {
				if (!ans)	ans = p1; 
				else{ ans_p->next = p1; }
				break;
			}
			else{
				x = y = q->next;
				count = 1;
				while (count < k){
					x = x->next;
					y->next = q;
					q = y;
					y = x;
					count++;
				}
				if (!ans) { ans = q; ans_p = p1; }
				else { ans_p->next = q; ans_p = p1; }
				q = p;
			}
			if (!p) break;
		}
		return ans;
	}
};






發佈了60 篇原創文章 · 獲贊 8 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章