链表专题(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!")
}
相关推荐
花酒锄作田6 天前
Gin 框架中的规范响应格式设计与实现
golang·gin
郝学胜-神的一滴6 天前
深入理解链表:从基础到实践
开发语言·数据结构·c++·算法·链表·架构
样例过了就是过了6 天前
LeetCode热题100 环形链表 II
数据结构·算法·leetcode·链表
网小鱼的学习笔记6 天前
leetcode876:链表的中间结点
数据结构·链表
qwfys2006 天前
How to install golang 1.26.0 to Ubuntu 24.04
ubuntu·golang·install
网小鱼的学习笔记6 天前
leetcode328:奇偶链表
数据结构·链表
codeejun6 天前
每日一Go-25、Go语言进阶:深入并发模式1
开发语言·后端·golang
石牌桥网管6 天前
Go 泛型(Generics)
服务器·开发语言·golang
小二·6 天前
Go 语言系统编程与云原生开发实战(第21篇)
开发语言·云原生·golang
小二·6 天前
Go 语言系统编程与云原生开发实战(第20篇)
开发语言·云原生·golang