Teaching Kids Programming: Videos on Data Structures and Algorithms
Introduction to Queue Data structure
Queue is a First In First Out (FIFO) data structure. Unlike stack, we use pop(0) to deque (remove the first element from the queue). We use q[0] to peek as compared to q[-1] to peek a stack.
We also use the len(q) and len(stack) to get the size of the current queue or stack respectively.
The following is a simple example that makes use of a queue to deque elements from a list and transform the numbers by squaring each.
1 2 3 4 5 6 | def sqr(nums): ans = [] while len(nums) > 0: x= nums.pop(0) ans.append(x) return ans |
def sqr(nums): ans = [] while len(nums) > 0: x= nums.pop(0) ans.append(x) return ans
We can reverse the output by simply changing pop(0) to pop() thus treating the input nums as a stack.
–EOF (The Ultimate Computing & Technology Blog) —
GD Star Rating
loading...
269 wordsloading...
Last Post: Algorithms to Compute the Kth Last Node of a Linked List
Next Post: Diagonal Sorting Algorithm in a Matrix