Chapter 2Chapter 2
Stacks, Queues andStacks, Queues and
HashingHashing
By : Dumindu PahalawattaBy : Dumindu Pahalawatta
MSc. CS , BIT, MBCS, MCAD, MCSMSc. CS , BIT, MBCS, MCAD, MCS
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.
Stack Model
 Input to a stack is by push
 Access is by top
 Deletion is by pop
Important stack applicationsImportant stack applications
 Compiler Design
 Mathematical Expression Evaluation
 Balanced Spell Checker
 Simple Calculator
The stack operations
 push() –push() – Insert element on top of stack.Insert element on top of stack.
 pop() -pop() - Removes and returns the top mostRemoves and returns the top most
element of the stack.element of the stack.
 peek() –peek() – Read the top value on the stackRead 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.
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
Array Implementation
import 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;
}}
//---------------------------------//---------------------------------
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);
}}
}}
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(" ");
}}
String Reverse ApplicationString Reverse Application
import 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;
}}
//---------------------------------//---------------------------------
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);
}}
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 kbd
if( input.equals("") ) // quit if [Enter]if( input.equals("") ) // quit if [Enter]
break;break;
// make a Reverser// make a Reverser
Reverser 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
class Reverserclass Reverser
{{
private String input; // input stringprivate String input; // input string
private 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 size
StackX 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 input
theStack.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
Delimiter ExampleDelimiter Example
class 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 size
StackX theStack = new StackX(stackSize); // make stackStackX theStack = new StackX(stackSize); // make stack
for(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 char
switch(ch)switch(ch)
{{
case '{': case '[': case '(': // the opening symbolscase '{': case '[': case '(': // the opening symbols
theStack.push(ch); // push themtheStack.push(ch); // push them
break;break;
case '}': case ']': case ')': // closing symbolscase '}': case ']': case ')': // closing symbols
if( !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 check
if( (ch=='}' && chx!='{') || (ch==']' && chx!='[') ||if( (ch=='}' && chx!='{') || (ch==']' && chx!='[') ||
(ch==')' && chx!='(') )(ch==')' && chx!='(') )
System.out.println("Error: "+ch+" at "+j);System.out.println("Error: "+ch+" at "+j);
}}
else // prematurely emptyelse // prematurely empty
System.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 processed
if( !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
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
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 kbd
if( 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;
} //---------------------------------} //---------------------------------
} //} //
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);
else
System.out.print("Can't insert, stack is full");
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.
QueueQueue
Queue 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()
 There are various queues quietly doing their job in ourThere 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 theThere'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 theA queue also stores keystroke data as we type at the
keyboard.keyboard.
 This way, if we are using a word processor but theThis way, if we are using a word processor but the
computer is briefly doing something else when we hitcomputer is briefly doing something else when we hit
a key, the keystroke won't be lost; it waits in the queuea 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 inUsing a queue guarantees the keystrokes stay in
order until they can be processed.order until they can be processed.
A Circular QueueA Circular Queue
 When we insert a new item in the queue in the WorkshopWhen we insert a new item in the queue in the Workshop
applet, the Front arrow moves upward, toward higher numbers in theapplet, 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 peoplewe may find the arrangement counter-intuitive, because the people
in a line at the movies all move forward, toward the front, whenin 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 deletedWe 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 theInstead 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 theTo 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 aroundqueue 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
Array implementation of queueArray implementation of queue
public 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;
}
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;
}
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();
}
}
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 fromWe 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() (orIf we restrict ourself to insertLeft() and removeLeft() (or
their equivalents on the right), then the deque acts like atheir equivalents on the right), then the deque acts like a
stack.stack.
 If we restrict ourself to insertLeft() and removeRight() (orIf 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 thanA deque provides a more versatile data structure than
either a stack or a queue, and is sometimes used ineither a stack or a queue, and is sometimes used in
container class libraries to serve both purposes.container class libraries to serve both purposes.
Priority QueuesPriority Queues
 A priority queue is a more specialized data structureA 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 ofHowever, it's a useful tool in a surprising number of
situations.situations.
 Like an ordinary queue, a priority queue has a frontLike 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 keyHowever, in a priority queue, items are ordered by key
value, so that the item with the lowest key (or in somevalue, so that the item with the lowest key (or in some
implementations the highest key) is always at theimplementations the highest key) is always at the
front.front.
 Items are inserted in the proper position to maintainItems are inserted in the proper position to maintain
the order.the order.
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.
Java Implementation of Priority QueueJava Implementation of Priority Queue
import java.io.*; // for I/O
////////////////////////////////////////////////////////////////
class PriorityQ
{
// array in sorted order, from max at 0 to min at size-1
private int maxSize;
private double[] queArray;
private int nItems;
//-------------------------------------------------------------
public PriorityQ(int s) // constructor
{
maxSize = s;
queArray = new double[maxSize];
nItems = 0;
}
public void insert(double item) // insert item
{
int j;
if(nItems==0) // if no items,
queArray[nItems++] = item; // insert at 0
else // 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 upward
else // if smaller,
break; // done shifting
} // end for
queArray[j+1] = item; // insert it
nItems++;
} // end else (nItems > 0)
} // end insert()
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
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 while
System.out.println(" ");
} // end main()
//-------------------------------------------------------------
} // end class PriorityQApp
Efficiency of Priority QueuesEfficiency of Priority Queues
 In the priority-queue implementation we showIn the priority-queue implementation we show
here, insertion runs in O(N) time, while deletionhere, insertion runs in O(N) time, while deletion
takes O(1) time.takes O(1) time.
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.
Hash TableHash Table
A2
A3
A5
0
1
2
3
4
5
6
7
8
Subscripts indicate
the home positions
of the keys being
hashed.
Hash FunctionsHash Functions
 Perfect hash functionPerfect hash function - if- if hh transformstransforms
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 timesearch 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.
Hash FunctionsHash Functions
 Some specific types of hash functions are:Some specific types of hash functions are:

DivisionDivision

h(k) = K mod TSizeh(k) = K mod TSize Tsize = sizeof(table)Tsize = sizeof(table)

Usually the preferred choice for the hash functionUsually the preferred choice for the hash function
if very little is known about the keys.if very little is known about the keys.
 FoldingFolding

In this number is divided into number of parts, andIn this number is divided into number of parts, and
these parts are sometimes reversed and thenthese parts are sometimes reversed and then
added together. Finally the last three digit of theadded 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 789
Mid part can be reversedMid part can be reversed
123+654+789 = 1566123+654+789 = 1566
Last three digits = 566Last three digits = 566
h(k) = 566h(k) = 566
 Mid-Square FunctionMid-Square Function
The key is squared and the middle or mid part ofThe key is squared and the middle or mid part of
the result is used as the address. If the key is athe result is used as the address. If the key is a
string, it has to be pre-processed to produce astring, 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.
 ExtractionExtraction
Only a part of the key is used to compute theOnly a part of the key is used to compute the
address. For the key 123-45-6789 this methodaddress. 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
 Radix TransformationRadix Transformation
The key is transformed into another numberThe key is transformed into another number
base.base.
e.g. If K is the decimal number 345, then itse.g. If K is the decimal number 345, then its
value in base 9 is 423. This value is thenvalue in base 9 is 423. This value is then
divided modulo TSize, and the resultingdivided modulo TSize, and the resulting
number is used as the address of the locationnumber is used as the address of the location
to which K should be hashed.to which K should be hashed.

Stack, queue and hashing

  • 1.
    Chapter 2Chapter 2 Stacks,Queues andStacks, Queues and HashingHashing By : Dumindu PahalawattaBy : Dumindu Pahalawatta MSc. CS , BIT, MBCS, MCAD, MCSMSc. CS , BIT, MBCS, MCAD, MCS
  • 2.
    StacksStacks  A stackis 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.
  • 3.
    Stack Model  Inputto a stack is by push  Access is by top  Deletion is by pop
  • 4.
    Important stack applicationsImportantstack applications  Compiler Design  Mathematical Expression Evaluation  Balanced Spell Checker  Simple Calculator
  • 5.
    The stack operations push() –push() – Insert element on top of stack.Insert element on top of stack.  pop() -pop() - Removes and returns the top mostRemoves and returns the top most element of the stack.element of the stack.  peek() –peek() – Read the top value on the stackRead 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.
  • 6.
    Implementation Of StacksImplementationOf 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
  • 7.
    Array Implementation import java.io.*;importjava.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; }} //---------------------------------//---------------------------------
  • 8.
    public double pop()publicdouble 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); }} }}
  • 9.
    class StackAppclass StackApp {{ publicstatic 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(" "); }}
  • 10.
    String Reverse ApplicationStringReverse Application import 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; }} //---------------------------------//---------------------------------
  • 11.
    public char pop()publicchar 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); }}
  • 12.
    class ReverseAppclass ReverseApp {{ publicstatic 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 kbd if( input.equals("") ) // quit if [Enter]if( input.equals("") ) // quit if [Enter] break;break; // make a Reverser// make a Reverser Reverser 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
  • 13.
    class Reverserclass Reverser {{ privateString input; // input stringprivate String input; // input string private 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 size StackX 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 input theStack.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
  • 14.
    Delimiter ExampleDelimiter Example classBracketCheckerclass 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 size StackX theStack = new StackX(stackSize); // make stackStackX theStack = new StackX(stackSize); // make stack for(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 char switch(ch)switch(ch) {{ case '{': case '[': case '(': // the opening symbolscase '{': case '[': case '(': // the opening symbols theStack.push(ch); // push themtheStack.push(ch); // push them break;break; case '}': case ']': case ')': // closing symbolscase '}': case ']': case ')': // closing symbols if( !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 check if( (ch=='}' && chx!='{') || (ch==']' && chx!='[') ||if( (ch=='}' && chx!='{') || (ch==']' && chx!='[') || (ch==')' && chx!='(') )(ch==')' && chx!='(') ) System.out.println("Error: "+ch+" at "+j);System.out.println("Error: "+ch+" at "+j); }} else // prematurely emptyelse // prematurely empty System.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 processed if( !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 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  • 15.
    class BracketsAppclass BracketsApp {{ publicstatic 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 kbd if( 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; } //---------------------------------} //--------------------------------- } //} //
  • 16.
    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); else System.out.print("Can't insert, stack is full");
  • 17.
    Efficiency of StacksEfficiencyof 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.
  • 18.
    QueueQueue Queue is simplya 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()
  • 21.
     There arevarious queues quietly doing their job in ourThere 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 theThere'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 theA queue also stores keystroke data as we type at the keyboard.keyboard.  This way, if we are using a word processor but theThis way, if we are using a word processor but the computer is briefly doing something else when we hitcomputer is briefly doing something else when we hit a key, the keystroke won't be lost; it waits in the queuea 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 inUsing a queue guarantees the keystrokes stay in order until they can be processed.order until they can be processed.
  • 22.
    A Circular QueueACircular Queue  When we insert a new item in the queue in the WorkshopWhen we insert a new item in the queue in the Workshop applet, the Front arrow moves upward, toward higher numbers in theapplet, 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 peoplewe may find the arrangement counter-intuitive, because the people in a line at the movies all move forward, toward the front, whenin 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 deletedWe 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 theInstead 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 theTo 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 aroundqueue 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
  • 23.
    Array implementation ofqueueArray implementation of queue public 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; }
  • 24.
    public void enqueue(Objectel) { 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; }
  • 25.
    public void printAll() { for(inti=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(); } }
  • 26.
    DequesDeques  A dequeis a double-ended queue.A deque is a double-ended queue.  We can insert items at either end and delete them fromWe 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() (orIf we restrict ourself to insertLeft() and removeLeft() (or their equivalents on the right), then the deque acts like atheir equivalents on the right), then the deque acts like a stack.stack.  If we restrict ourself to insertLeft() and removeRight() (orIf 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 thanA deque provides a more versatile data structure than either a stack or a queue, and is sometimes used ineither a stack or a queue, and is sometimes used in container class libraries to serve both purposes.container class libraries to serve both purposes.
  • 27.
    Priority QueuesPriority Queues A priority queue is a more specialized data structureA 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 ofHowever, it's a useful tool in a surprising number of situations.situations.  Like an ordinary queue, a priority queue has a frontLike 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 keyHowever, in a priority queue, items are ordered by key value, so that the item with the lowest key (or in somevalue, so that the item with the lowest key (or in some implementations the highest key) is always at theimplementations the highest key) is always at the front.front.  Items are inserted in the proper position to maintainItems are inserted in the proper position to maintain the order.the order.
  • 28.
    Here’s how themail 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.
  • 29.
    Java Implementation ofPriority QueueJava Implementation of Priority Queue import java.io.*; // for I/O //////////////////////////////////////////////////////////////// class PriorityQ { // array in sorted order, from max at 0 to min at size-1 private int maxSize; private double[] queArray; private int nItems; //------------------------------------------------------------- public PriorityQ(int s) // constructor { maxSize = s; queArray = new double[maxSize]; nItems = 0; }
  • 30.
    public void insert(doubleitem) // insert item { int j; if(nItems==0) // if no items, queArray[nItems++] = item; // insert at 0 else // 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 upward else // if smaller, break; // done shifting } // end for queArray[j+1] = item; // insert it nItems++; } // end else (nItems > 0) } // end insert()
  • 31.
    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
  • 32.
    class PriorityQApp { public staticvoid 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 while System.out.println(" "); } // end main() //------------------------------------------------------------- } // end class PriorityQApp
  • 33.
    Efficiency of PriorityQueuesEfficiency of Priority Queues  In the priority-queue implementation we showIn the priority-queue implementation we show here, insertion runs in O(N) time, while deletionhere, insertion runs in O(N) time, while deletion takes O(1) time.takes O(1) time.
  • 34.
    Introduction to HashingIntroductionto 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.
  • 35.
    Hash TableHash Table A2 A3 A5 0 1 2 3 4 5 6 7 8 Subscriptsindicate the home positions of the keys being hashed.
  • 36.
    Hash FunctionsHash Functions Perfect hash functionPerfect hash function - if- if hh transformstransforms 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 timesearch 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.
  • 37.
    Hash FunctionsHash Functions Some specific types of hash functions are:Some specific types of hash functions are:  DivisionDivision  h(k) = K mod TSizeh(k) = K mod TSize Tsize = sizeof(table)Tsize = sizeof(table)  Usually the preferred choice for the hash functionUsually the preferred choice for the hash function if very little is known about the keys.if very little is known about the keys.
  • 38.
     FoldingFolding  In thisnumber is divided into number of parts, andIn this number is divided into number of parts, and these parts are sometimes reversed and thenthese parts are sometimes reversed and then added together. Finally the last three digit of theadded 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 789 Mid part can be reversedMid part can be reversed 123+654+789 = 1566123+654+789 = 1566 Last three digits = 566Last three digits = 566 h(k) = 566h(k) = 566
  • 39.
     Mid-Square FunctionMid-SquareFunction The key is squared and the middle or mid part ofThe key is squared and the middle or mid part of the result is used as the address. If the key is athe result is used as the address. If the key is a string, it has to be pre-processed to produce astring, 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.
  • 40.
     ExtractionExtraction Only apart of the key is used to compute theOnly a part of the key is used to compute the address. For the key 123-45-6789 this methodaddress. 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
  • 41.
     Radix TransformationRadixTransformation The key is transformed into another numberThe key is transformed into another number base.base. e.g. If K is the decimal number 345, then itse.g. If K is the decimal number 345, then its value in base 9 is 423. This value is thenvalue in base 9 is 423. This value is then divided modulo TSize, and the resultingdivided modulo TSize, and the resulting number is used as the address of the locationnumber is used as the address of the location to which K should be hashed.to which K should be hashed.