Implementation of the stack of Python algorithm

Source: Internet
Author: User
In this paper, the implementation of stack in Python algorithm is presented as an example, which has some referential value for learning data structure domain algorithm. The specific contents are as follows:

1. Stack stack common operations:

Stack () to create an empty stack object
Push () Adds an element to the topmost layer of the stack
Pop () removes the topmost element of the stack and returns this element
Peek () returns the topmost element and does not delete it
IsEmpty () Determine if the stack is empty
Size () returns the number of elements in the stack

2. Simple case and operation result:

Stack operation      Stack Contents   Return Value s.isempty ()   []        True S.push (4)   [4]  s.push (' dog ')   [4, ' dog ']  s.peek ()   [4, ' dog ']    ' dog ' S.push (True)   [4, ' dog ', True]  s.size ()   [4, ' Dog ', True]   3 s.isempty ()   [4, ' dog ', True]   False s.push (8.4)   [4, ' dog ', true,8.4]  s.pop ()       [4, ' dog ', true]   8.4 s.pop ()       [4, ' dog ']     True s.size ()   [4, ' dog ']     2

This uses the Python list object to simulate the implementation of the stack, with the following code:

#coding: Utf8class stack: "" "  Analog Stack" ""  def __init__ (self):    self.items = []      def isEmpty (self):    Return Len (self.items) ==0     def push (self, item):    self.items.append (item)    def pops (self):    return Self.items.pop ()     def peek (self):    if not Self.isempty ():      return Self.items[len (Self.items)-1]      def size (self):    return len (self.items) S=stack () print (S.isempty ()) S.push (4) s.push (' Dog ') print (S.peek ()) S.push (True) print (S.size ()) print (S.isempty ()) s.push (8.4) print (S.pop ()) print (S.pop ()) print (S.size ())

Interested readers can try to test the example code described in this article, I believe you will learn python can have a certain harvest.

  • 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.