兩種解法搞定Swap Nodes in Pairs演算法題

freephp發表於2024-04-18

最近還是很喜歡用golang來刷演算法題,更接近通用演算法,也沒有像動態指令碼語言那些語法糖,真正靠實力去解決問題。
下面這道題很有趣,也是一道連結串列題目,具體如下:

24. Swap Nodes in Pairs
Solved
Medium
Topics
Companies
Given a linked list, swap every two adjacent nodes and return its head. You must solve the problem without modifying the values in the list's nodes (i.e., only nodes themselves may be changed.)
 

Example 1:


Input: head = [1,2,3,4]
Output: [2,1,4,3]
Example 2:

Input: head = []
Output: []
Example 3:

Input: head = [1]
Output: [1]
 

Constraints:

The number of nodes in the list is in the range [0, 100].
0 <= Node.val <= 100

快速思考了一下,想到這個交換節點的事兒可以用遞迴去實現,透過三個指標prev, current, next不斷移動,實現相鄰節點交換,程式碼如下:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
	
	if head == nil || head.Next == nil {
		return head
	}
	
	if head.Next.Next == nil {
		next := head.Next
		head.Next = nil
		next.Next = head
        head = next

		return head
	}

	prev, cur, nxt := head, head.Next, head.Next.Next
    cur.Next = prev
    head = cur
	prev.Next = swapPairs(nxt)

    return head
}

遞迴雖然好,但是也會有一些效能上的擔憂,畢竟遞迴呼叫太深,可能會引發堆疊溢位。後面再仔細推敲了一下,完全可以用2個指標不斷進行交換,可以不用遞迴。這裡還是要用一個dump節點來方便的儲存修改後的連結串列,具體如下:

/**
 * Definition for singly-linked list.
 * type ListNode struct {
 *     Val int
 *     Next *ListNode
 * }
 */
func swapPairs(head *ListNode) *ListNode {
	
	dump := &ListNode{Val: 0}
	dump.Next = head
	prevNode := dump
	currentNode := head

    for currentNode != nil && currentNode.Next != nil {
		prevNode.Next = currentNode.Next
		currentNode.Next = currentNode.Next.Next
		prevNode.Next.Next = currentNode
		prevNode = currentNode
		currentNode = currentNode.Next
	}

	return dump.Next
}

最終它們的時間複雜度是O(N),空間複雜度O(1),都非常棒。如果是你,你更喜歡哪種解法呢?歡迎在評論區留言交流。

相關文章