两种解法搞定Swap Nodes in Pairs算法题

最近还是很喜欢用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),都非常棒。如果是你,你更喜欢哪种解法呢?欢迎在评论区留言交流。

相关推荐
不会聊天真君64715 小时前
基础语法·中(golang笔记第二期)
开发语言·笔记·golang
zdl68616 小时前
搭建Golang gRPC环境:protoc、protoc-gen-go 和 protoc-gen-go-grpc 工具安装教程
开发语言·后端·golang
FatHonor18 小时前
【golang学习之旅】使用VScode安装配置Go开发环境
vscode·学习·golang
ん贤19 小时前
AI大模型落地系列:一文读懂 Eino 的 Memory 与 Session(持久化对话)
大数据·ai·golang·eino
Anastasiozzzz20 小时前
告别 Class:深入理解 Go 语言的面向对象编程
开发语言·后端·golang
F1FJJ21 小时前
一个 CLI 工具的开源迭代记录:从单二进制到全平台分发
网络·网络协议·docker·golang·开源·开源软件
雨师@21 小时前
多个golang版本如何切换的办法
开发语言·后端·golang
qiumingxun21 小时前
【Go】Go语言基础学习(Go安装配置、基础语法)
服务器·学习·golang
2501_941982051 天前
Go 语言实现企业微信外部群消息主动推送方案
开发语言·golang·企业微信
无心水1 天前
【时间利器】5、多语言时间处理实战:Go/C#/Rust/Ruby统一规范
golang·rust·c#·时间·分布式架构·openclaw·openclaw变现