LeetCode 25. K 個一組翻轉鏈表(Java版)

題目

25. K 個一組翻轉鏈表

https://leetcode-cn.com/problems/reverse-nodes-in-k-group/
在這裏插入圖片描述

題解

我的指針的做法

我是喜歡用迭代來進行翻轉的所以我這裏還是用了迭代的思想。
先找到需要反轉的鏈表,然後翻轉,然後在進行拼接。看起來很簡單,我們我們先遍歷需要反轉的鏈表段子,也就是先走過k個ListNode。然後用幾個變量先記錄下當前的鏈表的情況。
reverse(start,end) 表示翻轉start到end的鏈表,並且返回反轉後的頭結點。
在這裏插入圖片描述
在這裏插入圖片描述

public ListNode reverseKGroup(ListNode head, int k) {
	if (head == null || head.next == null) {
		return head;
	}
	ListNode dummy= new ListNode(0);
	ListNode pre = dummy;
	ListNode cur = head;
	pre.next = cur;
	ListNode start = null;
	ListNode end = null;
	ListNode after = null;
	while (cur != null) {
		boolean isEnd = false;
		start = cur;
		for (int i = 0; i < k-1; i++) {
			if (cur == null) {
				isEnd = true;
				break;
			}
			cur = cur.next;
		}
		if (isEnd || cur == null) {
			break;
		}
		end = cur;
		after = cur.next;
		pre.next = reserve(start, end);
		start.next = after;
		pre = start;
		cur = after;
	}
	return dummy.next;
}

// 反轉鏈表
private ListNode reserve(ListNode start, ListNode end) {
	ListNode pre = null;
	ListNode current = start;
	ListNode after = null;
	while (pre != end && current != null) {
		after = current.next;
		current.next = pre;
		pre = current;
		current = after;
	}
	return end;
}

用棧的思想就很簡單了,但是應該是不符合的題目的不能用額外的空間這個條件

public ListNode reverseKGroup(ListNode head, int k) {
    if (head == null || head.next == null) {
        return head;
    }
    Stack<ListNode> stack = new Stack<>();
    boolean isFirst = true;
    ListNode dummyNode = new ListNode(0);
    ListNode pre = dummyNode;
    while (true) {
        int count = 0;
        ListNode temp = head;
        // 開始填棧,要麼到了尾結點,要麼棧的元素的數量等於k
        while (temp != null && count < k) {
            stack.push(temp);
            temp = temp.next;
            count++;
        }
        // 到了尾結點了。
        if (count < k) {
            pre.next = head;
            break;
        }
        // 根據棧裏的元素進行反轉
        while (!stack.isEmpty()) {
            pre.next = stack.pop();
            pre = pre.next;
        }
        // 爲了防止下一個沒滿足反轉的條件,直接退出的情況
        pre.next = temp;
        head = temp;
    }
    return dummyNode.next;
}
發佈了139 篇原創文章 · 獲贊 13 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章