链表专题(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!")
}
相关推荐
ChineHe1 小时前
Gin框架基础篇001_路由与路由组详解
后端·golang·gin
laozhoy12 小时前
深入理解Go语言errors.As方法:灵活的错误类型识别
开发语言·后端·golang
周杰伦_Jay2 小时前
【Go 语言】核心特性、基础语法及面试题
开发语言·后端·golang
ezreal_pan4 小时前
基于券类型路由的渐进式重构:函数式选项模式与管道模式的完美结合
设计模式·重构·golang·选项函数
顾安r4 小时前
12.17 脚本工具 自动化全局跳转
linux·前端·css·golang·html
金枪不摆鳍5 小时前
算法2-链表
数据结构·算法·链表
Henry_Wu0015 小时前
go与c# 及nats和rabbitmq交互
golang·c#·rabbitmq·grpc·nats
Asus.Blogs5 小时前
golang格式化打印json
javascript·golang·json
Clarence Liu5 小时前
Go Context 深度解析:从源码到 RESTful 框架的最佳实践
开发语言·后端·golang
古城小栈6 小时前
性能边界:何时用 Go 何时用 Java 的技术选型指南
java·后端·golang