DEV Community

Cover image for Stack Data Structure
Aya Bouchiha
Aya Bouchiha

Posted on • Edited on

3 2

Stack Data Structure

Hello, in this article we're going to talk about stack;

Definition of Stack

"A stack is a linear data structure that stores items in a Last-In/First-Out (LIFO) or First-In/Last-Out (FILO) manner. In stack, a new element is added at one end and an element is removed from that end only. The insert and delete operations are often called push and pop."

stack data structure

Space and Time complexity

the space complexity of a stack is O(n)

push pop peek
O(1) O(1) O(1)

implementation of a stack using list in python

class Stack :
    def __init__(self):
        self.items = []
        self.top = 0

    def push(self,data: any) -> any :
        self.items.append(data)
        self.top+=1
        return data

    def pop(self) -> any:
        if self.top > 0 :
            self.top -=1
            return self.items.pop()
    def peek(self) -> any:
        if self.top > 0:
            return self.items[-1]

    def __len__(self) -> int:
        return self.top

    def clear(self) -> list:
        self.items = []
        self.top = 0
        return self.items

    def isEmpty(self) -> bool:
        return self.items == []

    def printAll(self) -> list:
        return self.items
Enter fullscreen mode Exit fullscreen mode

References and useful Ressources

thank you!
#day_2

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️