Debian Codegraph @

stacks/linkedliststack/linkedliststack.go

raw symbols SCIP
1 // Copyright (c) 2015, Emir Pasic. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
4
5 // Package linkedliststack implements a stack backed by a singly-linked list.
6 //
7 // Structure is not thread safe.
8 //
9 // Reference:https://en.wikipedia.org/wiki/Stack_%28abstract_data_type%29#Linked_list
10 package linkedliststack
11
12 import (
13 "fmt"
14 "strings"
15
16 "github.com/emirpasic/gods/v2/lists/singlylinkedlist"
17 "github.com/emirpasic/gods/v2/stacks"
18 )
19
20 // Assert Stack implementation
21 var _ stacks.Stack[int] = (*Stack[int])(nil)
22
23 // Stack holds elements in a singly-linked-list
24 type Stack[T comparable] struct {
25 list *singlylinkedlist.List[T]
26 }
27
28 // New nnstantiates a new empty stack
29 func New[T comparable]() *Stack[T] {
30 return &Stack[T]{list: singlylinkedlist.New[T]()}
31 }
32
33 // Push adds a value onto the top of the stack
34 func (stack *Stack[T]) Push(value T) {
35 stack.list.Prepend(value)
36 }
37
38 // Pop removes top element on stack and returns it, or nil if stack is empty.
39 // Second return parameter is true, unless the stack was empty and there was nothing to pop.
40 func (stack *Stack[T]) Pop() (value T, ok bool) {
41 value, ok = stack.list.Get(0)
42 stack.list.Remove(0)
43 return
44 }
45
46 // Peek returns top element on the stack without removing it, or nil if stack is empty.
47 // Second return parameter is true, unless the stack was empty and there was nothing to peek.
48 func (stack *Stack[T]) Peek() (value T, ok bool) {
49 return stack.list.Get(0)
50 }
51
52 // Empty returns true if stack does not contain any elements.
53 func (stack *Stack[T]) Empty() bool {
54 return stack.list.Empty()
55 }
56
57 // Size returns number of elements within the stack.
58 func (stack *Stack[T]) Size() int {
59 return stack.list.Size()
60 }
61
62 // Clear removes all elements from the stack.
63 func (stack *Stack[T]) Clear() {
64 stack.list.Clear()
65 }
66
67 // Values returns all elements in the stack (LIFO order).
68 func (stack *Stack[T]) Values() []T {
69 return stack.list.Values()
70 }
71
72 // String returns a string representation of container
73 func (stack *Stack[T]) String() string {
74 str := "LinkedListStack\n"
75 values := []string{}
76 for _, value := range stack.list.Values() {
77 values = append(values, fmt.Sprintf("%v", value))
78 }
79 str += strings.Join(values, ", ")
80 return str
81 }
82
83 // Check that the index is within bounds of the list
84 func (stack *Stack[T]) withinRange(index int) bool {
85 return index >= 0 && index < stack.list.Size()
86 }