Docsity

Data Structures and Algorithms: Stacks and Queues - Prof. David J. Galles, Papers of Data Structures and Algorithms

Partial preview of the text

Download Data Structures and Algorithms: Stacks and Queues - Prof. David J. Galles and more Papers Data Structures and Algorithms in PDF only on Docsity!

Data Structures and Algorithms^ CS245-2009S-04Stacks and Queues

David GallesDepartment of Computer ScienceUniversity of San Francisco

04-0:^ Abstract Data Types^ An Abstract Data Type is a definition of a typebased on the operations that can be performed onit.^ An ADT is an

interface Data in an ADT cannot be manipulated directly –only through operations defined in the interface

04-2:^ Stack A Stack is a Last-In, First-Out (LIFO) data structure.Stack Operations:^ Add an element to the top of the stack^ Remove the top element^ Check if the stack is empty

04-3:^ Stack Implementation Array:

04-5:^ Stack Implementation^ See code & Visualizaion

04-6:^ Θ()^ For Stack Operations Array Implementation:pushpopempty()

04-8:^ Stack Implementation Linked List:

04-9:^ Stack Implementation Linked List:^ Stack elements are stored in a linked list^ Top of the stack is the

front^ of the linked list push: top = new Link(elem, top) pop: elem = top.element(); top = top.next()

04-11:^ Θ()^ For Stack Operations Linked List Implementation:pushpopempty()

04-12:^ Θ()^ For Stack Operations Linked List Implementation:push^ Θ(1)^ pop^ Θ(1)^ empty()^ Θ(1)

04-14:^ Queue Implementation Linked List:

04-15:^ Queue Implementation Linked List:^ Maintain a pointer to the first and last element inthe Linked List^ Add elements to the back of the Linked List^ Remove elements from the front of the linked list^ Enqueue:^ tail.setNext(new link(elem,null));tail = tail.next()^ Dequeue:^ elem = head.element();head = head.next();

04-17:^ Queue Implementation Array:

04-18:^ Queue Implementation Array:^ Store queue elements in a circular array^ Maintain the index of the first element (head) andthe next location to be inserted (tail)^ Enqueue:^ data[tail] = elem;tail = (tail + 1) % size^ Dequeue:^ elem = data[head];head = (head + 1) % size