链表专题(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!")
}
相关推荐
2501_941982055 小时前
深度对比:Java、Go、Python 实现企微外部群推送,哪个效率更高?
java·golang·企业微信
TracyCoder1239 小时前
LeetCode Hot100(26/100)——24. 两两交换链表中的节点
leetcode·链表
季明洵9 小时前
C语言实现单链表
c语言·开发语言·数据结构·算法·链表
only-qi9 小时前
leetcode19. 删除链表的倒数第N个节点
数据结构·链表
参.商.11 小时前
【Day 27】121.买卖股票的最佳时机 122.买卖股票的最佳时机II
leetcode·golang
牛奔11 小时前
如何理解 Go 的调度模型,以及 G / M / P 各自的职责
开发语言·后端·golang
牛奔13 小时前
Go 是如何做抢占式调度的?
开发语言·后端·golang
wengqidaifeng14 小时前
数据结构(三)栈和队列(上)栈:计算机世界的“叠叠乐”
c语言·数据结构·数据库·链表
only-qi15 小时前
leetcode24两两交换链表中的节点 快慢指针实现
数据结构·算法·链表
清云随笔15 小时前
Golang基础
golang