Algorithms, Blockchain and Cloud

Teaching Kids Programming – Reversing a List using Stack


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.

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.

def rev(nums):
  ans = []
  while len(nums) > 0:
     x = nums.pop()
     ans.append(x)
  return ans

–EOF (The Ultimate Computing & Technology Blog) —

204 words
Last Post: Teaching Kids Programming - Computing Fibonacci Numbers using 3 Methods
Next Post: Even Frequency of Array using Sort or Hash Map

The Permanent URL is: Teaching Kids Programming – Reversing a List using Stack (AMP Version)

Exit mobile version