1. python implements the Stack. You can first write the stack class to the file stack. py, use from Stack import Stack in other program files, and then use the stack. The stack. py program is as follows:
Class Stack (): def _ init _ (self, size): self. size = size; self. stack = []; self. top =-1; def push (self, ele): # Check whether the stack is full before stack entry if self. isfull (): raise exception ("out of range"); else: self. stack. append (ele); self. top = self. top + 1; def pop (self): # Check whether the stack is empty if self. isempty (): raise exception ("stack is empty"); else: self. top = self. top-1; return self. stack. pop (); def isfull (self): return self. top + 1 = self. size; def isempty (self): return self. top =-1;
Write another program file, stacktest. py, and use the stack. The content is as follows:
#!/usr/bin/python from stack import Stacks=Stack(20);for i in range(3):s.push(i);s.pop()print s.isempty();
2. python queue implementation:
Class Queue (): def _ init _ (self, size): self. size = size; self. front =-1; self. rear =-1; self. queue = []; def enqueue (self, ele): # if self. isfull (): raise exception ("queue is full"); else: self. queue. append (ele); self. rear = self. rear + 1; def dequeue (self): # if self. isempty (): raise exception ("queue is empty"); else: self. front = self. front + 1; return self. queue [self. front]; def isfull (self): return self. rear-self.front + 1 = self. size; def isempty (self): return self. front = self. rear; q = Queue (10); for I in range (3): q. enqueue (I); print q. dequeue (); print q. isempty ();