链表专题(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!")
}
相关推荐
(づど)5 小时前
解决VSCode中安装Go环境Gopls失败的问题
vscode·golang
wavemap19 小时前
先到先得:免费订阅一年ChatGPT Go会员
开发语言·chatgpt·golang
浮尘笔记20 小时前
Go并发编程核心:Mutex和RWMutex的用法
开发语言·后端·golang
百***06011 天前
【Golang】——Gin 框架中的表单处理与数据绑定
microsoft·golang·gin
百***93501 天前
【Golang】——Gin 框架中间件详解:从基础到实战
中间件·golang·gin
hweiyu001 天前
数据结构:循环链表
数据结构·链表
Tony Bai1 天前
Go 2025 密码学年度报告:后量子时代的防御与 FIPS 的“纯 Go”革命
开发语言·后端·golang·密码学
Like_wen1 天前
idea/goland 无法创建目标目录
java·golang
一起养小猫1 天前
《Java数据结构与算法》第三篇(中)——从Char到泛型:链栈的抽象、递归的瓦解与栈模拟实现
java·开发语言·数据结构·算法·链表