Python stack and queue method, python stack queue
This article describes how to implement the stack and queue in python. Share it with you for your reference. The specific analysis is as follows:
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.
Stack. py program:
Copy codeThe Code 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 going into the stack
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 before exiting the 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;
Write another program file, stacktest. py, and use the stack. The content is as follows:
Copy codeThe Code is 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 queue implementation:
Copy codeThe Code is as follows: class Queue ():
Def _ init _ (self, size ):
Self. size = size;
Self. front =-1;
Self. rear =-1;
Self. queue = [];
Def enqueue (self, ele): # queue operations
If self. isfull ():
Raise exception ("queue is full ");
Else:
Self. queue. append (ele );
Self. rear = self. rear + 1;
Def dequeue (self): # team-out operations
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 Python programming.