Python stack and queue

Source: Internet
Author: User

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. The stack. py program 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 stack entry 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 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:

#!/usr/bin/python from stack import Stacks=Stack(20);for i in range(3):s.push(i);s.pop()print s.isempty();

2. python queue implementation:

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 ();

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.