Stack Algorithm

The Stack Using Array Algorithm is an efficient data structure that implements the stack concept using an array as its underlying storage mechanism. The stack is a linear data structure that follows the Last-In-First-Out (LIFO) order, where the last element added to the stack is the first one to be removed. It consists of two main operations: pushing (adding) an element onto the stack and popping (removing) the element from the top of the stack. The array-based implementation of this algorithm allows for fast and easy access to the stack's top element, making it a popular choice for various applications such as parsing, expression evaluation, and function call management. In the array-based stack implementation, an integer variable called "top" is used to keep track of the index of the topmost element in the stack. When a new element is pushed onto the stack, the "top" index is incremented, and the element is placed at that index in the array. Conversely, when an element is popped from the stack, the "top" index is decremented, effectively removing the element from the stack. One of the key considerations for this algorithm is the stack's capacity, which is determined by the size of the underlying array. When the stack becomes full, it may require resizing (either by doubling or shrinking) to accommodate additional elements or to conserve memory. This dynamic resizing can be implemented using a dynamic array or by allocating and deallocating memory as needed. Overall, the Stack Using Array Algorithm offers a simple and efficient method for implementing a stack data structure with constant time complexity for both push and pop operations, making it an attractive choice for a wide range of applications.
package StackLinkedList

type Node struct {
	data int
	next *Node
}

type Stack struct {
	top *Node
}

func (list *Stack) Push(i int) {
	data := &Node{data: i}
	if list.top != nil {
		data.next = list.top
	}
	list.top = data
}

func (list *Stack) Pop() (int, bool) {
	if list.top == nil {
		return 0, false
	}
	i := list.top.data
	list.top = list.top.next
	return i, true
}

func (list *Stack) Peek() (int, bool) {
	if list.top == nil {
		return 0, false
	}
	return list.top.data, true
}

func (list *Stack) Get() []int {

	var items []int

	current := list.top
	for current != nil {
		items = append(items, current.data)
		current = current.next
	}
	return items
}

func (list *Stack) IsEmpty() bool {
	return list.top == nil
}

func (list *Stack) Empty() {
	list.top = nil
}

LANGUAGE:

DARK MODE: