[Getting Started with Algorithms and Data Structures] Using Python Arrays to Implement a Stack

Implement a stack

Title description:

1. The use 数组of a data structure that implements a stack requires the following methods:

  • Push the stack: insert elements at the top of the stack
  • Bouncing stack: pop the top element of the stack
  • Get the top element of the stack
  • Determine if the stack is empty
  • Get the number of elements in the stack

2. Stack operation

  • Create a new stack (named s1)
  • Push the array ls_1 from small to large by index
  • Number of elements in the output stack
  • Get the top element of the stack, save it in the variable s1_gettop, and observe the number of elements in the stack
  • Pop the top element of the stack, save it in the variable s1_poptop, and observe the number of elements in the stack

prompt

1. Stack

Insert picture description here

Introduction

  • A commonly used data structure
  • LIFO-last in first out: the last inserted element comes out first

Note:

  • Getting the top element of the stack does not change the stack itself
  • Popping the top element of the stack is based on obtaining the top element of the stack, and then performing a stack operation to change the stack. You can use the popmethods in the list

2. Problem analysis

class MyStack:
    
    def __init__(self):
        self.items = []
        
    # 判断栈是否为空
    def is_empty(self):
        return len(self.items) == 0
    
    # 获取栈中元素个数
    def size(self):
        return len(self.items)
    
    # 返回栈顶元素
    def get_top(self):
        #先判断栈是否为空,如果不为空返回栈顶元素,否则返回 None
        if not self.is_empty():
            return self.items[self.size() - 1]  # 可以改为 return self.items[-1]
        
        else:
            return None
        
    #弹栈
    def my_pop(self):
        #先判断栈是否为空,如果不为空弹出栈顶元素,否则打印“栈已为空”,返回None
        if not self.is_empty():
            return self.items.pop()
        else:
            print("栈已为空!")
            return None
    
    #压栈
    def my_push(self,item):  # 注意这里有两个参数
        self.items.append(item)
        
# 数组ls_1
ls_1 = list(range(1,10,2))
ls_1
[1, 3, 5, 7, 9]

New stack s1

s1 = MyStack()
s1
<__main__.MyStack at 0x6f27d08>

Push the array ls_1 from small to large by index

for i in ls_1:
    s1.my_push(i)

Number of elements in the output stack

print(s1.size())
5

Get the top element of the stack, save it in the variable s1_gettop, and print the number of elements in the stack

s1_gettop = s1.get_top()
print('栈顶元素为:{}'.format(s1_gettop))
print('栈中元素个数为:{}'.format(s1.size()))
栈顶元素为:9
栈中元素个数为:5

Pop the top element of the stack, save it in the variable s1_poptop, print the number of elements in the stack

s1_poptop = s1.my_pop()
print('栈顶元素为:{}'.format(s1_poptop))
print('栈中元素个数为:{}'.format(s1.size()))
栈顶元素为:9
栈中元素个数为:4
# 拓展一下
class Student(object):
    def __init__(self,name,score):
        self.name = name
        self.score = score
    def get_grade(self):
        if self.score >= 90:
            return 'A'
        elif self.score >= 60:
            return 'B'
        else:
            return 'C'
lisa = Student('Lisa',99)
bart = Student('Bart',59)
print(lisa.name,lisa.get_grade())
print(bart.name,bart.get_grade())
            
Lisa A
Bart C
Published 42 original articles · praised 28 · visits 4961

Guess you like

Origin blog.csdn.net/KaelCui/article/details/105364571