Simple Stack in python

Here's a bare bones Stack in python.  Really not sure if my earlier one is even a stack now.  It had so many access points and places you could alter it.  The more I learn about these things, the more they seem to have different names and methods based on how people can use them alter them and access them.  I just shot for trying to alter them and access them as much as possible. 

So,  a Bare Bones Stack:




class StackNode(object):
    def __init__(self, data, node):
     
        self.data = data
        self.next = node

    def __repr__(self):

        nval = self.next and self.next.data or None
        return f"[{self.data}: {repr(nval)}]"

class StackList(object):

    def __init__(self):
        self.stack = None

    def push(self, obj):
        # add a newnode to the stack.
        #  [ data,  None]
        #  [ data,  None][ <----,  data][<----, data] .......
        end = self.stack
        if end == None:
            newnode = StackNode(obj, None)
            self.stack = newnode
        else:
            newnode = StackNode(obj,None)
            #[ DATA,  ( / )]
            newnode.next = self.stack
            #[ stack, ( / )][ DATA, <----]
            self.stack = newnode
            # stack = [ DATA, <----]

    def count(self):
        # get a length
        node = self.stack
        count = 0
        if node:
            while node:           
                node = node.next
                count +=1
        return count

    def graphical(self):
        # print off a representation of the stack

        node = self.stack
        length = self.count()
        if node:
            print("\n\n")
            while node:
                if length == 1:
                    print(f"[ (1){node.data}, (/) ]")
                    node = node.next
                else:   
                    print(f"[({length}){node.data}----> ]")
                    length -= 1
                    node = node.next


        else:
            print(" EMPTY ")

    def top(self):
        # Zeds 'top'  reference to first item?
        node = self.stack
        if node:
           return node.data
        else:
            return None

    def pop(self):
        # take the top of the list off
        node = self.stack
        if node:
            #[DATA, (/)][DATA, <---]
            #[DATA, (/)][DATA, <---][DATA, <----]
            self.stack = node.next
        else:
            print(" EMPTY ")
            return None
           
    def dump(self):
        self.stack = None

   

   

Comments

Popular posts from this blog

JavaScript Ascii animation with while loops and console.log

playing with trigonometry sin in pygame

JavaScript and a Matrix