stack, queue and hashing

41
Chapter 2 Chapter 2 Stacks, Queues and Stacks, Queues and Hashing Hashing By : Dumindu Pahalawatta By : Dumindu Pahalawatta MSc. CS , BIT, MBCS, MCAD, MSc. CS , BIT, MBCS, MCAD, MCS MCS

Upload: dumindu-pahalawatta

Post on 21-Mar-2017

229 views

Category:

Technology


3 download

TRANSCRIPT

Page 1: Stack, queue and hashing

Chapter 2Chapter 2Stacks, Queues andStacks, Queues and

HashingHashingBy : Dumindu PahalawattaBy : Dumindu Pahalawatta MSc. CS , BIT, MBCS, MCAD, MCSMSc. CS , BIT, MBCS, MCAD, MCS

Page 2: Stack, queue and hashing

StacksStacks A stack is a data structure in which all the

access is restricted to the most recently inserted items.

If we remove this item, then we can access the next-to-last item inserted, and etc.

A stack is also a handy aid for algorithms applied to certain complex data structures.

Page 3: Stack, queue and hashing

Stack Model Input to a stack is by push Access is by top Deletion is by pop

Page 4: Stack, queue and hashing

Important stack applicationsImportant stack applications

Compiler Design Mathematical Expression Evaluation Balanced Spell Checker Simple Calculator

Page 5: Stack, queue and hashing

The stack operations

push() – push() – Insert element on top of stack.Insert element on top of stack.

pop() - pop() - Removes and returns the top most Removes and returns the top most element of the stack.element of the stack.

peek() – peek() – Read the top value on the stack Read the top value on the stack without removing.without removing.

isEmpty – isEmpty – Checks the stack is empty or not.Checks the stack is empty or not.

isFull – isFull – Checks the stack is full or not.Checks the stack is full or not.

Page 6: Stack, queue and hashing

Implementation Of StacksImplementation Of Stacks

There are two basic ways to arrange for constant time operations. The first is to store the items contiguously in an

array. And the second is to store items non contiguously

in a linked list

Page 7: Stack, queue and hashing

Array Implementationimport java.io.*;import java.io.*;class StackXclass StackX{{

private int maxSize;private int maxSize;private double[] stackArray;private double[] stackArray;private int top;private int top;//---------------------------------//---------------------------------public StackX(int s)public StackX(int s){{

maxSize=s;maxSize=s;stackArray=new double[maxSize];stackArray=new double[maxSize];top=-1;top=-1;

}}//---------------------------------//---------------------------------public void push(double j)public void push(double j){{

stackArray[++top]=j;stackArray[++top]=j;}}//---------------------------------//---------------------------------

Page 8: Stack, queue and hashing

public double pop()public double pop(){{

return stackArray[top--];return stackArray[top--];}}public double peek()public double peek(){{

return stackArray[top];return stackArray[top];}}//---------------------------------//---------------------------------public boolean isEmpty()public boolean isEmpty(){{

return (top==-1);return (top==-1);}}//---------------------------------//---------------------------------public boolean isFull()public boolean isFull(){{

return (top==maxSize-1);return (top==maxSize-1);}}

}}

Page 9: Stack, queue and hashing

class StackAppclass StackApp{{

public static void main(String args[])public static void main(String args[]){{StackX theStack=new StackX(10);StackX theStack=new StackX(10);theStack.push(20);theStack.push(20);theStack.push(40);theStack.push(40);theStack.push(60);theStack.push(60);theStack.push(80);theStack.push(80);

while (!theStack.isEmpty())while (!theStack.isEmpty()){{double value=theStack.pop();double value=theStack.pop();System.out.println(value);System.out.println(value);System.out.println(" ");System.out.println(" ");}}System.out.println(" ");System.out.println(" ");}}

}}

Page 10: Stack, queue and hashing

String Reverse ApplicationString Reverse Applicationimport java.io.*;import java.io.*;class StackXclass StackX{{

private int maxSize;private int maxSize;private char[] stackArray;private char[] stackArray;private int top;private int top;//---------------------------------//---------------------------------public StackX(int s)public StackX(int s){{

maxSize=s;maxSize=s;stackArray=new char[maxSize];stackArray=new char[maxSize];top=-1;top=-1;

}}//---------------------------------//---------------------------------public void push(char j)public void push(char j){{

stackArray[++top]=j;stackArray[++top]=j;}}//---------------------------------//---------------------------------

Page 11: Stack, queue and hashing

public char pop()public char pop(){{return stackArray[top--];return stackArray[top--];}}public char peek()public char peek(){{return stackArray[top];return stackArray[top];}}//---------------------------------//---------------------------------public boolean isEmpty()public boolean isEmpty(){{return (top==-1);return (top==-1);}}//---------------------------------//---------------------------------public boolean isFull()public boolean isFull(){{return (top==maxSize-1);return (top==maxSize-1);}}

}}

Page 12: Stack, queue and hashing

class ReverseAppclass ReverseApp{{

public static void main(String[] args) throws IOExceptionpublic static void main(String[] args) throws IOException{{String input, output;String input, output;while(true)while(true){{System.out.print("Enter a string: ");System.out.print("Enter a string: ");System.out.flush();System.out.flush();input = getString(); // read a string from kbdinput = getString(); // read a string from kbdif( input.equals("") ) // quit if [Enter]if( input.equals("") ) // quit if [Enter]break;break;// make a Reverser// make a ReverserReverser theReverser = new Reverser(input);Reverser theReverser = new Reverser(input);output = theReverser.doRev(); // use itoutput = theReverser.doRev(); // use it

System.out.println("Reversed: " + output);System.out.println("Reversed: " + output);} // end while} // end while} // end main()} // end main()//--------------------------------------------------------------//--------------------------------------------------------------public static String getString() throws IOExceptionpublic static String getString() throws IOException{{InputStreamReader isr = new InputStreamReader(System.in);InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);BufferedReader br = new BufferedReader(isr);String s = br.readLine();String s = br.readLine();return s;return s;}}

} // end class ReverseApp} // end class ReverseApp

Page 13: Stack, queue and hashing

class Reverserclass Reverser{{

private String input; // input stringprivate String input; // input stringprivate String output; // output stringprivate String output; // output string//--------------------------------------------------------------//--------------------------------------------------------------public Reverser(String in) // constructorpublic Reverser(String in) // constructor{ { input = in; input = in; }}//--------------------------------------------------------------//--------------------------------------------------------------public String doRev() // reverse the stringpublic String doRev() // reverse the string{{int stackSize = input.length(); // get max stack sizeint stackSize = input.length(); // get max stack sizeStackX theStack = new StackX(stackSize); // make stackStackX theStack = new StackX(stackSize); // make stack

for(int j=0; j<input.length(); j++)for(int j=0; j<input.length(); j++){{char ch = input.charAt(j); // get a char from inputchar ch = input.charAt(j); // get a char from inputtheStack.push(ch); // push ittheStack.push(ch); // push it}}

output = "";output = "";

while( !theStack.isEmpty() )while( !theStack.isEmpty() ){{char ch = theStack.pop(); // pop a char,char ch = theStack.pop(); // pop a char,output = output + ch; // append to outputoutput = output + ch; // append to output}}

return output;return output;} // end doRev()} // end doRev()

} // end class Reverser} // end class Reverser

Page 14: Stack, queue and hashing

Delimiter ExampleDelimiter Exampleclass BracketCheckerclass BracketChecker{{

private String input; // input stringprivate String input; // input string//-------------------------//-------------------------public BracketChecker(String in) // constructorpublic BracketChecker(String in) // constructor{ input = in; }{ input = in; }//------------------------------------------------------//------------------------------------------------------public void check()public void check(){{int stackSize = input.length(); // get max stack sizeint stackSize = input.length(); // get max stack sizeStackX theStack = new StackX(stackSize); // make stackStackX theStack = new StackX(stackSize); // make stackfor(int j=0; j<input.length(); j++) // get chars in turnfor(int j=0; j<input.length(); j++) // get chars in turn{{char ch = input.charAt(j); // get charchar ch = input.charAt(j); // get charswitch(ch)switch(ch){ { case '{': case '[': case '(': // the opening symbolscase '{': case '[': case '(': // the opening symbolstheStack.push(ch); // push themtheStack.push(ch); // push thembreak;break;case '}': case ']': case ')': // closing symbolscase '}': case ']': case ')': // closing symbolsif( !theStack.isEmpty() ) // if stack not empty,if( !theStack.isEmpty() ) // if stack not empty,{ { char chx = theStack.pop(); // pop and checkchar chx = theStack.pop(); // pop and checkif( (ch=='}' && chx!='{') || (ch==']' && chx!='[') || (ch==')' && chx!='(') )if( (ch=='}' && chx!='{') || (ch==']' && chx!='[') || (ch==')' && chx!='(') )System.out.println("Error: "+ch+" at "+j);System.out.println("Error: "+ch+" at "+j);}}else // prematurely emptyelse // prematurely emptySystem.out.println("Error: "+ch+" at "+j);System.out.println("Error: "+ch+" at "+j);break;break;} // end switch} // end switch} // end for} // end for// at this point, all characters have been processed// at this point, all characters have been processedif( !theStack.isEmpty() )if( !theStack.isEmpty() )System.out.println("Error: missing right delimiter");System.out.println("Error: missing right delimiter");} // end check()} // end check()//------------------------------------------------------------’//------------------------------------------------------------’

} // end class BracketChecker} // end class BracketChecker////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Page 15: Stack, queue and hashing

class BracketsAppclass BracketsApp{{

public static void main(String[] args) throws IOExceptionpublic static void main(String[] args) throws IOException{{String input;String input;while(true)while(true){ { System.out.print("Enter string containing delimiters: ");System.out.print("Enter string containing delimiters: ");System.out.flush();System.out.flush();input = getString(); // read a string from kbdinput = getString(); // read a string from kbdif( input.equals("") ) // quit if [Enter]if( input.equals("") ) // quit if [Enter]break;break;BracketChecker theChecker = new BracketChecker(input); BracketChecker theChecker = new BracketChecker(input); theChecker.check(); // check bracketstheChecker.check(); // check brackets} // end while} // end while} // end main()} // end main()

//--------------------------------------------------//--------------------------------------------------public static String getString() throws IOExceptionpublic static String getString() throws IOException{ { InputStreamReader isr = new InputStreamReader(System.in);InputStreamReader isr = new InputStreamReader(System.in);BufferedReader br = new BufferedReader(isr);BufferedReader br = new BufferedReader(isr);String s = br.readLine();String s = br.readLine();return s;return s;} //---------------------------------} //---------------------------------

} //} //

Page 16: Stack, queue and hashing

Error HandlingError Handling There are different philosophies about how to handle stack

errors. What happens if you try to push an item onto a stack that's already full, or pop an item from a stack that's empty?

We've left the responsibility for handling such errors up to the class user. The user should always check to be sure the stack is not full before inserting an item:

if( !theStack.isFull() )insert(item);

elseSystem.out.print("Can't insert, stack is full");

Page 17: Stack, queue and hashing

Efficiency of StacksEfficiency of Stacks

Items can be both pushed and popped from the stack implemented in the StackX class in constant O(1) time.

That is, the time is not dependent on how many items are in the stack, and is therefore very quick.

No comparisons or moves are necessary.

Page 18: Stack, queue and hashing

QueueQueueQueue is simply a waiting line that grows by adding elements to its end and shrinks by taking elements from its front. Unlike a stack , a queue is a structure in which both ends are used : one for adding new elements and one for removing them. Therefore , the last element has to wait until all element has to wait until all elements preceding it on the queue are removed . A queue is an FIFO structure.

clear() – clear the queue

isEmpty() – check to see if the queue is empty

enqueue(el) – Put the element el at the end of the queue

dequeue() – Take first element from the queue

firstEl() - - return the first element or peek()

Page 19: Stack, queue and hashing
Page 20: Stack, queue and hashing
Page 21: Stack, queue and hashing

There are various queues quietly doing their job in our There are various queues quietly doing their job in our computer's (or the network's) operating system.computer's (or the network's) operating system.

There's a printer queue where print jobs wait for the There's a printer queue where print jobs wait for the printer to be available.printer to be available.

A queue also stores keystroke data as we type at the A queue also stores keystroke data as we type at the keyboard.keyboard.

This way, if we are using a word processor but the This way, if we are using a word processor but the computer is briefly doing something else when we hit computer is briefly doing something else when we hit a key, the keystroke won't be lost; it waits in the queue a key, the keystroke won't be lost; it waits in the queue until the word processor has time to read it.until the word processor has time to read it.

Using a queue guarantees the keystrokes stay in Using a queue guarantees the keystrokes stay in order until they can be processed.order until they can be processed.

Page 22: Stack, queue and hashing

A Circular QueueA Circular Queue When we insert a new item in the queue in the Workshop When we insert a new item in the queue in the Workshop

applet, the Front arrow moves upward, toward higher numbers in the applet, the Front arrow moves upward, toward higher numbers in the array.array.

When we remove an item, Front also moves upward.When we remove an item, Front also moves upward.

we may find the arrangement counter-intuitive, because the people we may find the arrangement counter-intuitive, because the people in a line at the movies all move forward, toward the front, when in a line at the movies all move forward, toward the front, when a person leaves the line.a person leaves the line.

We could move all the items in a queue whenever we deleted We could move all the items in a queue whenever we deleted one, but that wouldn't be very efficient.one, but that wouldn't be very efficient.

Instead we keep all the items in the same place and move the Instead we keep all the items in the same place and move the front and rear of the queue.front and rear of the queue.

To avoid the problem of not being able to insert more items into the To avoid the problem of not being able to insert more items into the queue even when it's not full, the Front and Rear arrows wrap around queue even when it's not full, the Front and Rear arrows wrap around to the beginning of the array. The result is a circular queueto the beginning of the array. The result is a circular queue

Page 23: Stack, queue and hashing

Array implementation of queueArray implementation of queuepublic class ArrayQueue{

private int first,last,size;private Object[] storage;public ArrayQueue(){

this(100);}public ArrayQueue(int n){

size=n;storage=new Object[size];first=last=-1;

}public boolean isFull(){

return first==0 && last==size-1 || first==last+1;}public boolean isEmpty(){

return first==-1;}

Page 24: Stack, queue and hashing

public void enqueue(Object el){

if(last==size-1 || last==-1){

storage[0]=el;last=0;if(first==-1)

first=0;}else

storage[++last]=el;}

public Object dequeue(){

Object tmp=storage[first];if(first==last)

last=first=-1;else if(first==size-1)

first=0;else

first++;return tmp;

}

Page 25: Stack, queue and hashing

public void printAll(){

for(int i=0;i<size;i++)System.out.print(storage[i]+" ");

}

public static void main(String args[]){

ArrayQueue o=new ArrayQueue();o.enqueue(52);o.enqueue(25);System.out.println(o.dequeue());System.out.println(o.dequeue());System.out.println(o.isFull());System.out.println(o.isEmpty());o.printAll();

}}

Page 26: Stack, queue and hashing

DequesDeques A deque is a double-ended queue.A deque is a double-ended queue. We can insert items at either end and delete them from We can insert items at either end and delete them from

either end.either end.

The methods might be called insertLeft() and insertRight(), The methods might be called insertLeft() and insertRight(), and removeLeft() and removeRight().and removeLeft() and removeRight().

If we restrict ourself to insertLeft() and removeLeft() (or If we restrict ourself to insertLeft() and removeLeft() (or their equivalents on the right), then the deque acts like a their equivalents on the right), then the deque acts like a stack.stack.

If we restrict ourself to insertLeft() and removeRight() (or If we restrict ourself to insertLeft() and removeRight() (or the opposite pair), then it acts like a queue.the opposite pair), then it acts like a queue.

A deque provides a more versatile data structure than A deque provides a more versatile data structure than either a stack or a queue, and is sometimes used in either a stack or a queue, and is sometimes used in container class libraries to serve both purposes.container class libraries to serve both purposes.

Page 27: Stack, queue and hashing

Priority QueuesPriority Queues A priority queue is a more specialized data structure A priority queue is a more specialized data structure

than a stack or a queue.than a stack or a queue.

However, it's a useful tool in a surprising number of However, it's a useful tool in a surprising number of situations. situations.

Like an ordinary queue, a priority queue has a front Like an ordinary queue, a priority queue has a front and a rear, and items are removed from the front.and a rear, and items are removed from the front.

However, in a priority queue, items are ordered by key However, in a priority queue, items are ordered by key value, so that the item with the lowest key (or in some value, so that the item with the lowest key (or in some implementations the highest key) is always at the implementations the highest key) is always at the front.front.

Items are inserted in the proper position to maintain Items are inserted in the proper position to maintain the order.the order.

Page 28: Stack, queue and hashing

Here’s how the mail sorting analogy applies to a priority queue. Every time the postman hands you a letter, you insert it into your pile of pending letters according to its priority. If it must be answered immediately (the phone company is about to disconnect your modem line), it goes on top, while if it can wait for a leisurely answer (a letter from your Aunt Mabel), it goes on the bottom.

Page 29: Stack, queue and hashing

Java Implementation of Priority QueueJava Implementation of Priority Queueimport java.io.*; // for I/O////////////////////////////////////////////////////////////////class PriorityQ{

// array in sorted order, from max at 0 to min at size-1private int maxSize;private double[] queArray;private int nItems;//-------------------------------------------------------------public PriorityQ(int s) // constructor{

maxSize = s;queArray = new double[maxSize];nItems = 0;

}

Page 30: Stack, queue and hashing

public void insert(double item) // insert item{

int j;if(nItems==0) // if no items,

queArray[nItems++] = item; // insert at 0else // if any items,{

for(j=nItems-1; j>=0; j--) // start at end,{

if( item > queArray[j] ) // if new item larger,queArray[j+1] = queArray[j]; // shift upwardelse // if smaller,

break; // done shifting} // end forqueArray[j+1] = item; // insert itnItems++;

} // end else (nItems > 0)} // end insert()

Page 31: Stack, queue and hashing

public double remove() // remove minimum item{

return queArray[--nItems]; }

public double peekMin() // peek at minimum item{ return queArray[nItems-1]; }

public boolean isEmpty() // true if queue is empty{ return (nItems==0); }

public boolean isFull() // true if queue is full{ return (nItems == maxSize); }

} // end class PriorityQ

Page 32: Stack, queue and hashing

class PriorityQApp{

public static void main(String[] args) throws IOException{

PriorityQ thePQ = new PriorityQ(5);thePQ.insert(30);thePQ.insert(50);thePQ.insert(10);thePQ.insert(40);thePQ.insert(20);while( !thePQ.isEmpty() ){

double item = thePQ.remove();System.out.print(item + " "); // 10, 20, 30, 40, 50

} // end whileSystem.out.println(" ");

} // end main()//-------------------------------------------------------------} // end class PriorityQApp

Page 33: Stack, queue and hashing

Efficiency of Priority QueuesEfficiency of Priority Queues

In the priority-queue implementation we show In the priority-queue implementation we show here, insertion runs in O(N) time, while deletion here, insertion runs in O(N) time, while deletion takes O(1) time.takes O(1) time.

Page 34: Stack, queue and hashing

Introduction to HashingIntroduction to Hashing A different approach to searching calculates the

position of the key in the table based on the value of the key.

The value of the key is the only indication of the position.

When the key is known, the position in the table can be accessed directly without making any test as in sequential binary search.

We need to find a function h that can transform a particular key K be it a string, number or record into an index in the table used for storing items of the same type as K. the function h is called hash function.

Page 35: Stack, queue and hashing

Hash TableHash Table

A2A3

A5

01234

5

67

8

Subscripts indicate the home positions of the keys being

hashed.

Page 36: Stack, queue and hashing

Hash FunctionsHash Functions

Perfect hash functionPerfect hash function - if - if hh transforms transforms different keys into different numbers. different keys into different numbers. - enables us to trivially build an - enables us to trivially build an O(1)O(1) search time search time

table. table. - the table should contain the same number of - the table should contain the same number of

positions as the number of elements being hashed.positions as the number of elements being hashed.

Page 37: Stack, queue and hashing

Hash FunctionsHash Functions Some specific types of hash functions are:Some specific types of hash functions are:

DivisionDivision h(k) = K mod TSize h(k) = K mod TSize Tsize = sizeof(table)Tsize = sizeof(table) Usually the preferred choice for the hash function Usually the preferred choice for the hash function

if very little is known about the keys.if very little is known about the keys.

Page 38: Stack, queue and hashing

FoldingFolding In this number is divided into number of parts, and In this number is divided into number of parts, and

these parts are sometimes reversed and then these parts are sometimes reversed and then added together. Finally the last three digit of the added together. Finally the last three digit of the sum or sum mod TableSize is used as the key.sum or sum mod TableSize is used as the key.

Ex:Ex:SSN : 123-45-6789 can be divide into 123 456 789SSN : 123-45-6789 can be divide into 123 456 789Mid part can be reversedMid part can be reversed123+654+789 = 1566123+654+789 = 1566Last three digits = 566Last three digits = 566h(k) = 566h(k) = 566

Page 39: Stack, queue and hashing

Mid-Square FunctionMid-Square Function The key is squared and the middle or mid part of The key is squared and the middle or mid part of

the result is used as the address. If the key is a the result is used as the address. If the key is a string, it has to be pre-processed to produce a string, it has to be pre-processed to produce a number.number.

e.g. if the key is 3121 then 3121e.g. if the key is 3121 then 31212 = 2 = 9740641 and9740641 and h(3121) = 406.h(3121) = 406.

Page 40: Stack, queue and hashing

ExtractionExtraction Only a part of the key is used to compute the Only a part of the key is used to compute the

address. For the key 123-45-6789 this method address. For the key 123-45-6789 this method might use themight use the

first four digits 1234first four digits 1234 last four digits 6789last four digits 6789 the first two combined with last two 1289 orthe first two combined with last two 1289 or some other combinationsome other combination

Page 41: Stack, queue and hashing

Radix TransformationRadix Transformation The key is transformed into another number The key is transformed into another number

base.base. e.g. If K is the decimal number 345, then its e.g. If K is the decimal number 345, then its

value in base 9 is 423. This value is then value in base 9 is 423. This value is then divided modulo TSize, and the resulting divided modulo TSize, and the resulting number is used as the address of the location number is used as the address of the location to which K should be hashed.to which K should be hashed.