算法第三週作業03

Description

Given a linked list, reverse the nodes of a linked list k at a time and return its modified list.

k is a positive integer and is less than or equal to the length of the linked 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

Solution

1. 對於第一組[0,k],可以從0開始讀節點node,另外在一個新鏈表head裏面寫,node.next = head, head = node ,從而實現倒序;

2. 使用遞歸方式對接下來的分組[k+1, 2k],[2k+1, 3k]...進行處理;

3. 首先需要讀取輸入鏈表的長度,然後判斷需要倒序的組數;

Code

public ListNode reverseKGroup(ListNode head, int k) {
		ListNode oldHead = head;
		int count = 0;
		// 獲取輸入鏈表的長度,得到需要遞歸的次數
		while(head != null){
			head = head.next;
			count++;
		}
		return recursion(oldHead, k, count/k);
	}
	
	public ListNode recursion(ListNode head, int k, int times){
		if(head != null && times != 0){
			ListNode oldHead = head;
			ListNode node1 = head;
			ListNode node2 = head.next;
			int i = 0;
			head = null;
			// 讀取輸入鏈表
			// 倒序寫入輸出鏈表
			while (i++ < k && node1 != null) {
				node1.next = head;
				head = node1;
				node1 = node2;
				if(node1 != null)
					node2 = node2.next;
			}
			// 遞歸操作接下來的節點
			oldHead.next = recursion(node1, k, times-1);
		}
		return head;
	}




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