TheAlgorithms/Go · error

stack list is empty

Error message

stack list is empty

What it means

SList.Peek returns the value at the top of the linked-list-backed stack without popping it. When the stack is empty, it returns this error (and an empty-string placeholder) because there is no top element. It is a misuse guard: callers must check IsEmpty() first.

Source

Thrown at structure/stack/stacklinkedlistwithlist.go:33

)

// SList is our struct that point to stack with container/list.List library
type SList struct {
	Stack *list.List
}

// Push add a value into our stack
func (sl *SList) Push(val any) {
	sl.Stack.PushFront(val)
}

// Peak is return last value that insert into our stack
func (sl *SList) Peek() (any, error) {
	if !sl.IsEmpty() {
		element := sl.Stack.Front()
		return element.Value, nil
	}
	return "", fmt.Errorf("stack list is empty")
}

// Pop is return last value that insert into our stack
// also it will remove it in our stack
func (sl *SList) Pop() (any, error) {
	if !sl.IsEmpty() {
		// get last element that insert into stack
		element := sl.Stack.Front()
		// remove element in stack
		sl.Stack.Remove(element)
		// return element value
		return element.Value, nil
	}
	return "", fmt.Errorf("stack list is empty")
}

// Length return length of our stack
func (sl *SList) Length() int {

View on GitHub (pinned to 5ba447ec5f)

Solutions

  1. Check sl.IsEmpty() before calling Peek().
  2. Handle the returned error and treat it as 'stack empty' rather than using the placeholder value.
  3. Ensure push operations actually execute before peek paths run (check control flow).

Example fix

// before
top, _ := sl.Peek()
compare(top)
// after
if sl.IsEmpty() {
    return // nothing on the stack
}
top, err := sl.Peek()
if err != nil {
    return err
}
compare(top)
Defensive patterns

Strategy: validation

Validate before calling

if sl.IsEmpty() {
    return errors.New("cannot peek: stack is empty")
}
top, err := sl.Peek()

Type guard

func peekSafe(sl *stack.SList) (any, bool) {
    if sl.IsEmpty() {
        return nil, false
    }
    v, err := sl.Peek()
    return v, err == nil
}

Try / catch

top, err := sl.Peek()
if err != nil {
    if strings.Contains(err.Error(), "empty") {
        return // stack empty, handle accordingly
    }
    return err
}

Prevention

When it happens

Trigger: Calling Peek() on an empty SList — a newly created stack, one whose elements were all popped, or one never pushed to.

Common situations: Balanced-parentheses / expression-evaluation code that peeks before verifying the stack has operands, or peeking after a drain loop in undo-history implementations.

Related errors


AI-assisted analysis of TheAlgorithms/Go@5ba447ec5f (2026-09-02). Data as JSON: /api/errors/e83c81a63133e719. Report an issue: GitHub.