Linear Structures: Stacks and Queues, Study notes of Computer Science

An introduction to linear structures, specifically focusing on stacks and queues. Linear structures are time-ordered data structures that reflect a temporal relationship. The concepts of first in first out (fifo) and last in first out (lifo) structures, their applications, and the conversion of infix to postfix expressions. It also discusses the implementation of stacks and queues using different methods, including array-based, arraylist-based, and reference-based approaches.

Typology: Study notes

Pre 2010

Uploaded on 11/08/2009

koofers-user-xf4-3
koofers-user-xf4-3 🇺🇸

9 documents

1 / 10

Toggle sidebar

This page cannot be seen from the preview

Don't miss anything!

bg1
1
CS200: Linear Structures
Stacks: Walls Ch. 7
Queues: Walls Ch. 8
Linear, time-ordered structures
Data structures that reflect a temporal relationship
order of removal based on order of insertion
We will consider:
“first come,first serve”
first in first out - FIFO (queue)
“take from the top of the pile”
last in first out - LIFO (stack)
Stacks
Last In First Out (LIFO) structure
A stack of dishes in a cafeteria
Add/Remove done from same end
5
4
3
2
1
top
Stack ADT
Create
Query
empty?
peek – return, but don't pop, the most recently
added element
Add
push - add (to the top of the stack)
Remove
pop - remove (from the top of the stack)
popAll - remove all
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download Linear Structures: Stacks and Queues and more Study notes Computer Science in PDF only on Docsity!

CS200: Linear Structures

 Stacks: Walls Ch. 7

 Queues: Walls Ch. 8

Linear, time-ordered structures

 Data structures that reflect a temporal relationship

 order of removal based on order of insertion

 We will consider:

 “first come,first serve”

 first in first out - FIFO (queue)

 “take from the top of the pile”

 last in first out - LIFO (stack)

Stacks

 Last In First Out (LIFO) structure

 A stack of dishes in a cafeteria

 Add/Remove done from same end

top

Stack ADT

 Create

 Query

 empty?

 peek – return, but don't pop, the most recently

added element

 Add

 push - add (to the top of the stack)

 Remove

 pop - remove (from the top of the stack)

 popAll - remove all

Applications - the run-time stack

 Nested method calls tracked on

call stack (aka run-time stack)

 First method that returns is the last one

invoked

 Element of call stack - activation

record

 parameters, return values

 local variables

 return address: pointer to next

instruction to be executed in calling

method (why?)

 pointer to previous stack top (why?)

http://en.wikipedia.org/wiki/Image:Call_stack_layout.svg

Applications -

Depth First Search

 Looking for a path in a

maze

 Strategy:

 Prioritize directions: right,

straight or left.

 At a dead end backtrack to

last choice point and try a

different direction

 Recursive solution?

 Stack-based solution?

out 0

4 in

Expressions

 Types of Algebraic Expressions

 Prefix

 Postfix (Reverse Polish Notation)

 Infix

 Prefix and postfix are easier to

parse. No need for brackets.

 Postfix: operator applies to the

operands that immediately precede

it.

 Which one is pre, in , post?

  1. 5 4 3 * -
  2. 5 * 4 - 3
  3. 5 * 4 3 -
      • 5 4 3

operands are

written in the

conventional way

Parsing and evaluating Postfix

while there are input tokens left

read the next token

if the token is a value

push it onto the stack.

else

//the token is a operator taking n arguments

pop the top n values from the stack and evaluate the

function

push the result on the stack

if there is only one value in the stack return it as the result

else return error

Do yourself

 a + b * c

 a – b / c + d

Infix to postfix with ()s

 operand: append to postfix expression

 order of operands in postfix same as in infix

 “(“: push on the stack

 “)”: pop operators off stack and append them to the

postfix expression until “(“ popped

 operator #:

 pop operators of greater or equal precedence off stack

and append to postfix expression until stack empty or

“(“ or strictly lower precedence operator encountered

 push operator # on the stack

 end of infix expression: append remaining operators

a-(b+c*d)/e

Ch stack postfix expr

a a

    • a

( -( a

b -( a b

  • -(+ a b

c -(+ a b c

  • -(+* a b c

d -(+* a b c d

) - a b c d * +

/ - / a b c d * +

e - / a b c d * + e

a b c d * + e / -

Checking for balanced braces

 How can we use a stack to determine

whether the braces in a string are balanced?

abc{defg{ijk}{l{mn}}op}qr

abc{def}}{ghij{kl}m

Stack Methods

push(in newItem:StackItemType) throws StackException

 adds a new item to the top of the stack

 Exception when insertion fails

pop():StackItemType throws StackException

 deletes the item at the top of the stack and returns it

 Exception when deletion fails

peek():StackItemType {query} throws StackException

 returns the top item from the stack, but does not remove it

 Exception when retrieval fails

Preconditions? Postconditions?

Array-Based Implementation

public class StackArrayBased implements StackInterface {

final int MAX_STACK 50; \ maximum size of stack

private Object items[];

private int top;

public StackArrayBased() {

items = new Object[MAX_STACK];

top = -1; }

public void push(Object newItem) throws Stack Exception{

if (!isFull()) {

items[++top] = newItem;

Why is it critical to

declare items and top

as private?

How is isFull implemented?

ArrayList Implementation

 push

 use add - add to the end of the ArrayList

 worst case complexity: O(n)

(but ONLY when capacity needs to be extended)

 pop

 use get(size–1) to obtain the return value

 use remove(size-1) to remove the element at the top

 peek

 use get(size–1)

 What if we push and pop at index 0?

public Stack implements StackInterface {

private ArrayList items;

Reference-based Implementation

public class StackReferenceBased implements StackInterface{

private Node top;

public StackReferenceBased() {

top = null;

public boolean isEmpty() {

return top == null;

public void push(Object newItem){

top = new Node(newItem, top);

Public class Node {

private Object item;

private Node next;

Queues

 First In First Out (FIFO) structure

 Imagine a checkout line

 So removing and adding are done from

opposite ends of structure.

 add to tail (back), remove from head (front)

 Used in operating systems (e.g. print queue).

Queue Methods

enqueue(in newItem:QueueItemType)

 Adds a new item to the tail of the queue

 Throws exception if not successful

dequeue():QueueItemType

 Deletes the item from the head of the queue and

returns it

 Throws exception if not successful

peek():QueueItemType

 Returns the item from the head of the queue

 Throws exception if not successful

Queue Implementation -

Using ArrayList

 enqueue

 use add - adds to the end of the ArrayList

 dequeue

 use get(0) to get return value

 use remove(0) to remove element from the queue

 peek

 use get(0)

How much time is required?

Naïve Array-Based Implementation

Drift can cause the queue to appear full

How do we initialize front and back?

(Hint: what does a queue with a single element look

like)

An Array-Based Implementation

 A wrap-around array eliminates the

problem of drift

 enqueue

back = (back+1) % MAX_QUEUE;

items[back] = newItem;

++count;

 Dequeue

frontItem = items[front];

front = (front+1) % MAX_QUEUE;

--count;

 peek

 return item at front

Initialization:

front to 0

back to MAX_QUEUE–

An Array-Based Implementation

The effect of some queue operations:

An Array-Based Implementation

 issue with the circular array implementation:

 front and back cannot be used to distinguish between

queue-full and queue-empty conditions

An Array-Based Implementation

front passes back when the queue becomes empty

Reference-Based Implementation

Inserting an item into a non-emtpy queue

Reference-Based Implementation

Inserting an item into an empty queue

Reference-Based Implementation

Deleting an item from a queue of more than one item

What happens when there is a single item?

Queue implementations

 What are the advantages/disadvantages of

the circular array / linked list

implementations?