链表专题(Golang)

中小厂手写题中最常见的是链表

LRU

用链表实现栈

go 复制代码
package main

import (
	"fmt"
)

type Node struct {
	Value int
	Next  *Node
}

type Stack struct {
	top *Node
}

// Push adds a new element to the top of the stack.
func (s *Stack) Push(value int) {
	newNode := &Node{Value: value, Next: s.top}
	s.top = newNode
}

// Pop removes the top element from the stack and returns its value.
// If the stack is empty, it returns -1 as an indicator.
func (s *Stack) Pop() int {
	if s.IsEmpty() {
		return -1 // Or any other sentinel value or error handling
	}
	value := s.top.Value
	s.top = s.top.Next
	return value
}

// Peek returns the value of the top element without removing it.
func (s *Stack) Peek() int {
	if s.IsEmpty() {
		return -1 // Or any other sentinel value or error handling
	}
	return s.top.Value
}

// IsEmpty checks if the stack is empty.
func (s *Stack) IsEmpty() bool {
	return s.top == nil
}

// Test function to verify the correctness of the stack implementation.
func testStack() {
	stack := &Stack{}

	// Test pushing elements
	stack.Push(10)
	stack.Push(20)
	stack.Push(30)

	// Test peeking the top element
	if stack.Peek() != 30 {
		fmt.Println("Peek failed")
	}

	// Test popping elements
	if stack.Pop() != 30 {
		fmt.Println("Pop failed for value 30")
	}
	if stack.Pop() != 20 {
		fmt.Println("Pop failed for value 20")
	}

	// Test popping from an empty stack should return -1
	if stack.Pop() != 10 {
		fmt.Println("Pop failed for value 10")
	}
	if stack.Pop() != -1 {
		fmt.Println("Pop from empty stack failed")
	}

	fmt.Println("All tests passed!")
}
相关推荐
飞川撸码3 小时前
【LeetCode 热题100】网格路径类 DP 系列题:不同路径 & 最小路径和(力扣62 / 64 )(Go语言版)
算法·leetcode·golang·动态规划
roman_日积跬步-终至千里10 小时前
【Go语言基础【14】】defer与异常处理(panic、recover)
golang
孔令飞11 小时前
Kubernetes 节点自动伸缩(Cluster Autoscaler)原理与实践
ai·云原生·容器·golang·kubernetes
chao_78911 小时前
链表题解——两两交换链表中的节点【LeetCode】
数据结构·python·leetcode·链表
笑口常开xpr16 小时前
数 据 结 构 进 阶:哨 兵 位 的 头 结 点 如 何 简 化 链 表 操 作
数据结构·链表·哨兵位的头节点
我的golang之路果然有问题17 小时前
云服务器部署Gin+gorm 项目 demo
运维·服务器·后端·学习·golang·gin
孔令飞18 小时前
Go 为何天生适合云原生?
ai·云原生·容器·golang·kubernetes
YGGP21 小时前
吃透 Golang 基础:数据结构之 Map
开发语言·数据结构·golang
march of Time21 小时前
go工具库:hertz api框架 hertz client的使用
开发语言·golang·iphone
余厌厌厌1 天前
go语言学习 第9章:映射(Map)
服务器·学习·golang