链表专题(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!")
}
相关推荐
不会写DN2 小时前
Golang中的map的key可以是哪些类型?可以嵌套map吗?
后端·golang·go
XWalnut3 小时前
LeetCode刷题 day16
数据结构·算法·leetcode·链表·动态规划
水蓝烟雨6 小时前
2071. 你可以安排的最多任务数目
数据结构·链表
止语Lab6 小时前
Go vs Java GC:同一场延迟战争的两条路
java·开发语言·golang
MmeD UCIZ9 小时前
GO 快速升级Go版本
开发语言·redis·golang
mOok ONSC10 小时前
对基因列表中批量的基因进行GO和KEGG注释
开发语言·数据库·golang
Achou.Wang12 小时前
go语言中类型别名和定义类型之间的区别
服务器·golang
geovindu12 小时前
go: Composite Pattern
设计模式·golang·组合模式
XMYX-013 小时前
18 - Go 等待协程:WaitGroup 使用与坑
开发语言·golang
XMYX-013 小时前
19 - Go 并发限制:限流与控制并发数
开发语言·golang