# -*- coding: utf-8 -*- class LinkedList: """A representation of a linked list of objects.""" def __init__(self): """Create an empty list.""" self.first = None def __len__(self): return self.count_nodes(self.first) def __str__(self): return self.show(self.first) def insert_as_first(self,x): """Insert an item to the first position of a list""" ny = Node(x) ny.next = self.first self.first = ny def append(self,x): """Add an item to the en of the list""" ny = Node(x) current_node=self.first if current_node==None: self.first=ny else: while current_node.next!=None: current_node=current_node.next current_node.next=ny def count_nodes(self, node): if node==None: return 0 else: nb=self.count_nodes(node.next) return 1+nb def pop(self): """Remove the first list object.""" x = self.first.value self.first = self.first.next return x def show(self, node): if node==None: return '' else: s=self.show(node.next) return str(node.value)+'\n'+s class Node: """An entry in a linked structure (e.g. Stack).""" def __init__(self, x): """Create a node linked to the given element.""" self.value = x self.next = None """Classroom exercise 1, example 1.""" class Stack: """A representation of a last-in-first-out (LIFO) stack of objects.""" def __init__(self): """Create an empty stack.""" self.top = None def __str__(self): return self.show(self.top) def show(self, node): if node==None: return '' else: s=self.show(node.next) return str(node.value)+'\n'+s def push(self,x): """Push an item onto the top of this stack.""" ny = Node(x) ny.next = self.top self.top = ny def pop(self): """Remove the top object from this stack and return it.""" x = self.top.value self.top = self.top.next return x def isempty(self): """Test if this stack is empty.""" ## The naïve solution (below) is unnecessary: # if self.top == None: # return True # else: # return False return self.top == None