This article illustrates how Python implements stacks and queues. Share to everyone for your reference. The specific analysis is as follows:
1, Python implementation stack, you can first write the stack class file stack.py, in other program files using the from stack import stack, and then you can use the stack.
stack.py Program:
Copy Code code as follows:
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 to see if stack is empty before stack
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, which reads as follows:
Copy Code code as follows:
#!/usr/bin/python
From stack import stack
S=stack (20);
For I in range (3):
S.push (i);
S.pop ()
Print S.isempty ();
2, Python implementation queue:
Copy Code code as follows:
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 ();
I hope this article will help you with your Python programming.