Python algorithm stack implementation, pythonstack

Source: Internet
Author: User
Tags python list

Python algorithm stack implementation, pythonstack

This article demonstrates the implementation of the stack in the Python algorithm in the form of an example, which has some reference value for learning the data structure domain algorithm. The details are as follows:

1. stack operations:

Stack () creates an empty Stack object
Push () adds an element to the top layer of the stack
Pop () deletes the top-level element of the stack and returns this element.
Peek () returns the top-level element and does not delete it.
IsEmpty () determines whether the stack is empty
Size () returns the number of elements in the stack.

2. Simple cases and operation results:

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

Here we use the python list object to simulate stack implementation. The specific code is as follows:

# Coding: utf8class Stack: "simulate Stack" def _ init _ (self): self. items = [] def isEmpty (self): return len (self. items) = 0 def push (self, item): self. items. append (item) def pop (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 ())

If you are interested, you can test the sample code described in this article. I believe it will be helpful for everyone to learn Python.


Implement a stack in Python

Class Stack:
# Creates an empty stack.
Def _ init _ (self ):
Self. _ theItems = list ()
# Returns True if the stack is empty or False otherwise.
Def isEmpty (self ):
Return len (self) = 0
# Returns the number of items in the stack.
Def _ len _ (self ):
Return len (self. _ theItems)
# Returns the top item on the stack without removing it.
Def peek (self ):
Assert not self. isEmpty (), "Cannot peek at an empty stack"
Return self. _ theItems [-1]
# Removes and returns the top item on the stack.
Def pop (self ):
Assert not self. isEmpty (), "Cannot pop from an empty stack"
Return self. _ theItems. pop ()
# Push an item onto the top of the stack.
Def push (self, item ):
Self. _ theItems. append (item)

In this book, you can search For 'Data ures and algorithms using python.

Write an algorithm to allow two sequential stacks to share an array of stacks [N] and implement inbound/outbound stack Operations respectively.

Two stacks are required to share a bucket. It seems that the top pointer of the stack can only start from both ends (a bit like the queue)
Set two stacks to s0, s1. The first stack top pointer of s1 is-1, and the first stack top pointer of s2 is N.
Typedef struct
{
Elemtype stack [N]; // stack storage space
Int top [2]; // top is the top pointer of two stacks.
} St;
St s; // s is a global variable for operations
Void push (int I, elemtype e) // The inbound stack operation. I indicates the number of the stack, and e indicates the inbound stack element.
{
If (I! = 0 | I! = 1) exit (0); // The stack number is incorrect.
If (s. top [1]-s. top [0] = 1) // full Stack
{
Printf ("FULL! ");
Return;
}
If (I = 0) s. tack [++ s. top [0] = e; // s0
If (I = 1) s. tack [-- s. top [1] = e; // s1
}
Void pop (int I, elemtype & e) // stack exit operation. I indicates the number of the stack, and e indicates the element of the stack.
{
If (I! = 0 | I! = 1) exit (0); // The stack number is incorrect.
If (I = 0)
{
If (s. top [0] =-1) // stack s0 null
{
Printf ("EMPTY! ");
Return;
}
Else e = s. stack [s. top [0] --]; // s0 outbound stack
}
If (I = 1)
{
If (s. top [1] = N) // stack s1 null
{
Printf ("EMPTY! ");
Return;
}
Else e = s. stack [s. top [1] ++]; // s1 outbound stack
}
}

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.