链表专题(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!")
}
相关推荐
紧跟先前的步伐9 小时前
Go AI Agent 实战 06|JSON 结构化输出与 Go 后端校验
人工智能·ai·golang
傅科摆 _ py20 小时前
链表力扣复习
数据结构·leetcode·链表
紧跟先前的步伐21 小时前
Go AI Agent 实战 08|HTTP 模型 API 的工作原理与请求流程
人工智能·http·ai·golang
紧跟先前的步伐21 小时前
Go AI Agent 实战 07|模型幻觉、能力边界与成本控制
大数据·人工智能·golang
利威尔xu1 天前
Go GMP 调度器 10 个高频追问:3 个线上故障让 P99 从 80ms 飙到 2s、10 万 goroutine 泄漏
开发语言·后端·面试·性能优化·golang
FfHUCisI1 天前
无锁 Reactor 网络模型与 gnet / evio 架构拆解
服务器·开发语言·后端·golang
y1su1 天前
Leetcode 链表,树,回溯 模板
java·leetcode·链表
紧跟先前的步伐1 天前
Go AI Agent 实战 05|Temperature 与生成参数:让模型输出可控
java·人工智能·golang
浮尘笔记2 天前
我用 Go 写了个手机端「远程 AI 开发控制台」(开源)
人工智能·智能手机·golang
microrain2 天前
专业版守核心,企业版做增量:SagooIoT 的跨模块能力出口
物联网·架构·golang·sagooiot