O(1) with LinkedList for all stack operations, clean and simple !


  • -1

    O(1) complexity for all stack operations. Take a look if you wish :)))

    class MyStack {
    public:
        /* data structure = Linked List */
        struct stackType
        {
            int val;
            stackType *next;
        };
        stackType *myStack = NULL; /* Stack Name = myStack */
        
        /* Push element x onto myStack */
        void push(int x) {
            if(myStack == NULL)
            {
                myStack = new stackType();
                myStack->val = x;
                myStack->next = NULL;
            }
            else
            {
                stackType *pik;
                pik = new stackType();
                pik->val = x;
                pik->next = myStack;
                myStack = pik;
            }
        }
        
        /** Removes the element on top of the stack and returns that element. */
        int pop() {
            stackType *pik = myStack;
            myStack = myStack->next;
            int ret = pik->val;
            delete(pik);
            return ret;
        }
        
        /* Get the top element. */
        int top() { return myStack->val; }
        
        /* Returns whether the stack is empty. */
        bool empty() { return myStack == NULL; }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.