链表专题(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!")
}
相关推荐
LuckyLay15 小时前
使用 Docker 搭建 Go Web 应用开发环境——AI教你学Docker
前端·docker·golang
{⌐■_■}20 小时前
【软件工程】tob和toc含义理解
前端·数据库·mysql·golang·软件工程·tidb
hackchen1 天前
Go与JS无缝协作:Goja引擎实战之错误处理最佳实践
开发语言·javascript·golang
YuTaoShao1 天前
【LeetCode 热题 100】141. 环形链表——快慢指针
java·算法·leetcode·链表
争不过朝夕,又念着往昔1 天前
Go语言反射机制详解
开发语言·后端·golang
Jerry Lau1 天前
go go go 出发咯 - go web开发入门系列(二) Gin 框架实战指南
前端·golang·gin
YuTaoShao2 天前
【LeetCode 热题 100】206. 反转链表——(解法一)值翻转
算法·leetcode·链表
YuTaoShao2 天前
【LeetCode 热题 100】142. 环形链表 II——快慢指针
java·算法·leetcode·链表
witton2 天前
Go语言网络游戏服务器模块化编程
服务器·开发语言·游戏·golang·origin·模块化·耦合
叹一曲当时只道是寻常2 天前
Softhub软件下载站实战开发(十六):仪表盘前端设计与实现
前端·golang