链表专题(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!")
}
相关推荐
Wang's Blog1 小时前
Go-Zero框架上手前奏2: 微服务核心要素 —— 拆分、通信与无状态设计
开发语言·微服务·golang
Generalzy18 小时前
从本地 Demo 到生产级检索:Milvus 学习笔记(2)
golang·milvus
小高Baby@19 小时前
单链表的删操作
数据结构·算法·golang
张3231 天前
Go语言基础 Map 函数值 闭包
开发语言·golang
北冥you鱼1 天前
Go Modules 使用指南:从入门到精通
开发语言·后端·golang
灯澜忆梦1 天前
【dp_1】爬楼梯 | 斐波那契数 | 第 N 个泰波那契数 | 三步问题
算法·golang
geovindu1 天前
go: Floyd-Warshall Algorithms
开发语言·后端·算法·golang
大侠锅锅2 天前
第 9 篇:状态机实践——状态环 + 步进表替代 if-else 地狱
golang·边缘计算·状态机
灯澜忆梦2 天前
iota枚举
golang
进击的程序猿~2 天前
Go Slice源码深度解析指南
开发语言·后端·golang