链表专题(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!")
}
相关推荐
李燚9 小时前
Eino 的 ReAct 循环是怎么跑起来的:图、节点、分支
golang·agent·react·ai-agent
Hiter_John12 小时前
Golang的运算符
开发语言·后端·golang
Hiter_John13 小时前
Golang的变量常量初始化
开发语言·后端·golang
必胜刻17 小时前
一个异步生成游戏功能的落地复盘:Redis Stream + WebSocket + 状态补偿
redis·websocket·golang·gin·状态补偿
绛洞花主敏明19 小时前
Go操作xorm中间表多对多关联实战
开发语言·后端·golang
pursue.dreams20 小时前
Windows系统Golang超详细安装配置教程(2026最新、零基础)
开发语言·windows·golang
小小龙学IT20 小时前
Go 后端并发实战:从 goroutine 到流水线架构
开发语言·架构·golang
lcj251120 小时前
【list】手撕C++ list!从0到1实现双向链表,迭代器、const迭代器、模板全解析,面试官都惊呆了!
c++·笔记·链表·list
代码中介商1 天前
LRU缓存算法:双向链表+哈希表实现
算法·链表·缓存
Hiter_John1 天前
Golang的循环语句
开发语言·算法·golang