链表专题(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!")
}
相关推荐
Q741_14718 小时前
力扣高频面试题详解 数组 链表 力扣 56.合并区间 力扣 160.相交链表 C++ 每日练习
c++·算法·leetcode·链表·数组·哈希
F1FJJ19 小时前
开源实践:用 Go 实现浏览器直连内网 RDP/SSH/VNC
运维·网络·网络协议·网络安全·golang·ssh
计算机安禾19 小时前
【数据结构与算法】第2篇:C语言核心机制回顾(一):指针、数组与结构体
c语言·开发语言·数据结构·c++·算法·链表·visual studio
呆萌很19 小时前
【GO】switch 练习题
golang
添尹1 天前
Go语言基础之变量和常量
golang
小刘不想改BUG2 天前
LeetCode 138.随机链表的复制 Java
java·leetcode·链表·hash table
参.商.2 天前
【Day43】49. 字母异位词分组
leetcode·golang
参.商.2 天前
【Day45】647. 回文子串 5. 最长回文子串
leetcode·golang
AMoon丶2 天前
Golang--内存管理
开发语言·后端·算法·缓存·golang·os
lars_lhuan2 天前
Go Context
golang