Teaching Kids Programming: Videos on Data Structures and Algorithms
Introduction to Stack
Stack is an important and commonly-used data structure that implements First In Last Out. The first item gets pop-ed out at last and the last inserted item gets pop-ed out first.
1 2 3 4 5 6 | st = [] st.append(1) # st = [1] st.append(2) # st = [1, 2] st.append(3) # st = [1, 2, 3] x = st.pop() # x = 3, and st = [1, 2] y = st.pop() # x = 2, and st = [1] |
st = [] st.append(1) # st = [1] st.append(2) # st = [1, 2] st.append(3) # st = [1, 2, 3] x = st.pop() # x = 3, and st = [1, 2] y = st.pop() # x = 2, and st = [1]
Reverse a List using Stack
A list in Python is inherent a Stack, which we can use the pop() to remove “last-inserted” item from the stack one by one and thus reversing the list.
1 2 3 4 5 6 | def rev(nums): ans = [] while len(nums) > 0: x = nums.pop() ans.append(x) return ans |
def rev(nums): ans = [] while len(nums) > 0: x = nums.pop() ans.append(x) return ans
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
221 wordsloading...
Last Post: Teaching Kids Programming - Computing Fibonacci Numbers using 3 Methods
Next Post: Even Frequency of Array using Sort or Hash Map