This article example describes the python implementation of stacks and queues. Shared for your reference. Specific analysis is as follows:
1, python implementation of the stack, you can first write the Stack class to the file, use from stack import Stack in other program files, and then you can use the stack.
Procedures for.
Copy Code The code is as follows.
class Stack():
def __init__(self,size):
=size;
=[];
=-1;
def push(self,ele): #Check if the stack is full before you put it on.
if ():
raise exception("out of range");
else:
(ele);
=+1;
def pop(self): # check if the stack is empty before leaving it
if ():
raise exception("stack is empty");
else:
=-1;
return ();
def isfull(self):
return +1==;
def isempty(self):
return ==-1;
def __init__(self,size):
=size;
=[];
=-1;
def push(self,ele): #Check if the stack is full before you put it on.
if ():
raise exception("out of range");
else:
(ele);
=+1;
def pop(self): # check if the stack is empty before leaving it
if ():
raise exception("stack is empty");
else:
=-1;
return ();
def isfull(self):
return +1==;
def isempty(self):
return ==-1;
Write another program file,,using the stack, as follows.
Copy Code The code is as follows.
#!/usr/bin/python
from stack import Stack
s=Stack(20);
for i in range(3):
(i);
()
print ();
from stack import Stack
s=Stack(20);
for i in range(3):
(i);
()
print ();
2, python implementation of the queue.
Copy Code The code is as follows.
class Queue():
def __init__(self,size):
=size;
=-1;
=-1;
=[];
def enqueue(self,ele): #Enqueue operation
if ():
raise exception("queue is full");
else:
(ele);
=+1;
def dequeue(self): #out-of-queue operation
if ():
raise exception("queue is empty");
else:
=+1;
return [];
def isfull(self):
return +1==;
def isempty(self):
return ==;
q=Queue(10);
for i in range(3):
(i);
print ();
print ();
def __init__(self,size):
=size;
=-1;
=-1;
=[];
def enqueue(self,ele): #Enqueue operation
if ():
raise exception("queue is full");
else:
(ele);
=+1;
def dequeue(self): #out-of-queue operation
if ():
raise exception("queue is empty");
else:
=+1;
return [];
def isfull(self):
return +1==;
def isempty(self):
return ==;
q=Queue(10);
for i in range(3):
(i);
print ();
print ();
I hope that what I have described in this article will help you in your Python programming.