""" A list implemetation of Stack CSCI 204, fall 2017 Xiannong Meng """ class Node: ''' A simple Node class ''' def __init__(self, data = None, next = None): self.data = data self.next = next class Stack: ''' A class of linked lists based stack Data attributes - self.top = a reference to the first Node in the list ''' def __init__(self, init_list = None): ''' Given a python list, creates a linked list. Initializes self.head as the start of the list Input: - initList: a python list ''' self.top = None if init_list is not None: self._create_list(init_list) def _create_list(self, init_list): ''' Given a python list, create a linked list''' for index in range(len(init_list)-1, -1, -1): self.top = Node(init_list[index], self.top) def __repr__(self): linkedList = "" curr_node = self.top while curr_node: linkedList += str(curr_node.data) + " -> " curr_node = curr_node.next return linked_list # ----------- BASIC OPERATIONS --------------# def push(self, data): """ Push a itemm to the top of the stack """ node = Node(data) node.next = self.top self.top = node def pop(self): """ Pop the top item from the stack """ assert not self.is_empty(), "Cannot pop an empty stack" data = self.top.data self.top = self.top.next return data def is_empty(self): """ Return True if stack is empty, False otherwise""" return self.top == None def peek(self): """ Return the data at the top of the stack""" assert not self.is_empty(), "Cannot peek at an empty stack" return self.top.data