80 likes | 264 Views
Stacks and Queues. Announcements. USACO Open competition results are out Congrats to Johnny for scoring 2nd in the US USACO Finalists are also announced Lynbrook has 3 finalists this year! Johnny Ho Steven Hao Jimmy Zeng That's probably more than any other school this year
E N D
Announcements • USACO Open competition results are out • Congrats to Johnny for scoring 2nd in the US • USACO Finalists are also announced • Lynbrook has 3 finalists this year! • Johnny Ho • Steven Hao • Jimmy Zeng • That's probably more than any other school this year • Officer elections • Check your email for the application/instructions later today • Stanford ProCo (5/19) registration • https://docs.google.com/forms/d/1uRV28nqDeS2UhO9FlKg-KR9EpyErNRlwnbfrq4jmYiM/viewform
Stacks and Queues • Two Operations: Push and Pop • Push: add an element to your list • Pop: remove an element from your list • Stack: Last in, first out • Example • Push 1, Push 5, Push 3, Pop [3] • Push 4, Pop [4] • Pop [5] • Queue: First in, first out • Example • Push 1, Push 5, Push 3, Pop[1] • Push 4, Pop[5] • Pop[3]
Singly Linked Lists • A data structure that can implement a stack or a queue • Supports insertions and deletions at any known location in constant time • Supports pushing to the front, pushing to the back, popping from the front • Store a head node and a tail node • Each node has a pointer to the next node • Ex. Push to the front: Make a new node, put it before the head, make it the new head.
Doubly Linked List • Like a linked list but supports popping from the back too • Stores almost the same thing as a linked list • Each node stores a "forward" pointer to the next node and a "reverse" pointer to the previous node • Ex. Pop from the back: Delete the tail, use the previous node as the new tail
Deque • A doubly linked list can implement a deque very easily • Deque can push/pop from front or back • Useful for job scheduling applications • Threads operate on jobs starting from the front-end of queues • Threads can move jobs from one back-end of a queue to another
Better deque Implementation • Circular buffer • An array that wraps around the back to the front • Store a head and tail in addition to the array • This supports: • Constant time pop/push from front/back • Constant time random access
POTW • Implement a queue with two stacks. • Your program should support the queue operations push(x) and pop() using only two stacks. Sample input: push 5 push 6 push 2 pop push 4 pop pop push 1 pop Sample output: 5 6 2 4 Constraints: N is the number of instructions (push and pop). 1<=N<=1000: 10 pts 1<=N<=500,000: 15 pts