This article mainly introduces how to implement the stack and queue in python, including the stack and queue definition methods and common operations, which has some reference value, for more information about how to implement the stack and queue in python, see the example in this article. 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:
The 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:
The 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:
The 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.