1. 程式人生 > >【leetcode】25. Reverse Nodes in k-Groups(JAVA)

【leetcode】25. Reverse Nodes in k-Groups(JAVA)

題目連結

提交程式碼:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
	public ListNode reverseKGroup(ListNode head, int k) {
		if (head == null || k == 1)
			return head;
		ListNode newhead =
new ListNode(-1); newhead.next = null; int i, cnt = 0; ListNode pmark = head; ListNode grouphead = newhead; ListNode p = head; ListNode pnext = p.next; ListNode nextgrouphead = p; while (pmark != null) { for (i = 0; i < k && pmark != null; i++) { // pmark會移動到下一個翻轉小組的第一個位置
pmark = pmark.next; cnt++; } // 退出迴圈之後如果cnt==k則翻轉小組中的結點個數有k個需要反轉 if (cnt == k) { for (i = 0; i < k; i++) { //頭插法 p.next = grouphead.next; grouphead.next = p; p = pnext; if (p != null) pnext = p.next; } grouphead = nextgrouphead; nextgrouphead =
p; cnt = 0; } else { grouphead.next = p; return newhead.next; } } return newhead.next; } }

執行結果: 在這裡插入圖片描述