This article mainly describes the Python implementation of the stack and queue method, including the stack and queue definition methods and common operations, with a certain reference value, the need for friends can refer to the following
The examples in this article describe how Python implements stacks and queues. Share to everyone for your reference. The specific analysis is as follows:
1, Python implementation of the stack, the stack class can be written to the file stack.py, in other program files using the from stack import stack, and then you can use the stack.
Stack.py of the program:
Class Stack (): def init (self,size): self.size=size; Self.stack=[]; Self.top=-1; def push (Self,ele): #入栈之前检查栈是否已满 if Self.isfull (): Raise Exception ("Out of Range"); else: self.stack.append (ele); self.top=self.top+1; def pop (self): # Check if stack is empty before stack is null 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;
Then write a program file, stacktest.py, using the stack, the content is as follows:
#!/usr/bin/python from stack import stack s=stack (a); For I in range (3): s.push (i); S.pop () print s.isempty ();
2. Python implementation queue:
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 ();