SlideShare ist ein Scribd-Unternehmen logo
1 von 41
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.

Weitere ähnliche Inhalte

Was ist angesagt?

Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
SANTOSH RATH
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
Maxim Zaks
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
Philip Schwarz
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
league
 

Was ist angesagt? (20)

Stack and Queue (brief)
Stack and Queue (brief)Stack and Queue (brief)
Stack and Queue (brief)
 
stack & queue
stack & queuestack & queue
stack & queue
 
U3.stack queue
U3.stack queueU3.stack queue
U3.stack queue
 
Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]Data Structures - Lecture 6 [queues]
Data Structures - Lecture 6 [queues]
 
Stacks and queues
Stacks and queuesStacks and queues
Stacks and queues
 
Mysql1
Mysql1Mysql1
Mysql1
 
Stacks
StacksStacks
Stacks
 
Stacks in c++
Stacks in c++Stacks in c++
Stacks in c++
 
Stack and its operations
Stack and its operationsStack and its operations
Stack and its operations
 
Standard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented ProgrammingStandard Template Library (STL) in Object Oriented Programming
Standard Template Library (STL) in Object Oriented Programming
 
Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)Queue Data Structure (w/ php egs)
Queue Data Structure (w/ php egs)
 
Mca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queueMca ii dfs u-3 linklist,stack,queue
Mca ii dfs u-3 linklist,stack,queue
 
linked list
linked listlinked list
linked list
 
Stack data structure in Data Structure using C
Stack data structure in Data Structure using C Stack data structure in Data Structure using C
Stack data structure in Data Structure using C
 
Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)Array Presentation (EngineerBaBu.com)
Array Presentation (EngineerBaBu.com)
 
Ds lab manual by s.k.rath
Ds lab manual by s.k.rathDs lab manual by s.k.rath
Ds lab manual by s.k.rath
 
Swift the implicit parts
Swift the implicit partsSwift the implicit parts
Swift the implicit parts
 
Monads do not Compose
Monads do not ComposeMonads do not Compose
Monads do not Compose
 
Modular Module Systems
Modular Module SystemsModular Module Systems
Modular Module Systems
 
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
Quicksort - a whistle-stop tour of the algorithm in five languages and four p...
 

Andere mochten auch

[Sirem 2012] Apprendimenti informali in Rete: una ricerca
[Sirem 2012] Apprendimenti informali in Rete: una ricerca[Sirem 2012] Apprendimenti informali in Rete: una ricerca
[Sirem 2012] Apprendimenti informali in Rete: una ricerca
Serena Triacca
 
Java Stack Traces
Java Stack TracesJava Stack Traces
Java Stack Traces
dbanttari
 
Healthy habits for healthy teeth (presentation)
Healthy habits for healthy teeth (presentation)Healthy habits for healthy teeth (presentation)
Healthy habits for healthy teeth (presentation)
Iryna Golovnia
 

Andere mochten auch (20)

PRESENTACIÓN PROYECTO FIN DE MÁSTER
PRESENTACIÓN PROYECTO FIN DE MÁSTER PRESENTACIÓN PROYECTO FIN DE MÁSTER
PRESENTACIÓN PROYECTO FIN DE MÁSTER
 
Enter my magic world.. Amaizing !!!!!!!!!!
  Enter my magic  world..   Amaizing  !!!!!!!!!!  Enter my magic  world..   Amaizing  !!!!!!!!!!
Enter my magic world.. Amaizing !!!!!!!!!!
 
[Sirem 2012] Apprendimenti informali in Rete: una ricerca
[Sirem 2012] Apprendimenti informali in Rete: una ricerca[Sirem 2012] Apprendimenti informali in Rete: una ricerca
[Sirem 2012] Apprendimenti informali in Rete: una ricerca
 
Biofest events organised by the Victorian Government
Biofest events organised by the Victorian GovernmentBiofest events organised by the Victorian Government
Biofest events organised by the Victorian Government
 
Escanear0054
Escanear0054Escanear0054
Escanear0054
 
Escanear0050
Escanear0050Escanear0050
Escanear0050
 
Java
JavaJava
Java
 
Java Stack Traces
Java Stack TracesJava Stack Traces
Java Stack Traces
 
Linked list (java platform se 8 )
Linked list (java platform se 8 )Linked list (java platform se 8 )
Linked list (java platform se 8 )
 
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 Data Structures - Lecture 9 [Stack & Queue using Linked List] Data Structures - Lecture 9 [Stack & Queue using Linked List]
Data Structures - Lecture 9 [Stack & Queue using Linked List]
 
Heap and stack space in java
Heap and stack space in javaHeap and stack space in java
Heap and stack space in java
 
Healthy habits for healthy teeth (presentation)
Healthy habits for healthy teeth (presentation)Healthy habits for healthy teeth (presentation)
Healthy habits for healthy teeth (presentation)
 
Java Stack (Pilha)
Java Stack (Pilha)Java Stack (Pilha)
Java Stack (Pilha)
 
Introduction to java and oop
Introduction to java and oopIntroduction to java and oop
Introduction to java and oop
 
Platone nella rete: cura dei contenuti e apprendimento
Platone nella rete: cura dei contenuti e apprendimentoPlatone nella rete: cura dei contenuti e apprendimento
Platone nella rete: cura dei contenuti e apprendimento
 
5. queue
5. queue5. queue
5. queue
 
03 Java Language And OOP Part III
03 Java Language And OOP Part III03 Java Language And OOP Part III
03 Java Language And OOP Part III
 
Queue
QueueQueue
Queue
 
Polymorphism
PolymorphismPolymorphism
Polymorphism
 
Tutti pazzi per lo storytelling
Tutti pazzi per lo storytellingTutti pazzi per lo storytelling
Tutti pazzi per lo storytelling
 

Ähnlich wie Stack, queue and hashing

Data structuresUsing java language and develop a prot.pdf
Data structuresUsing java language and develop a prot.pdfData structuresUsing java language and develop a prot.pdf
Data structuresUsing java language and develop a prot.pdf
armyshoes
 
6Modify the bfs.java program (Listing A) to find the minimu.docx
6Modify the bfs.java program (Listing  A) to find the minimu.docx6Modify the bfs.java program (Listing  A) to find the minimu.docx
6Modify the bfs.java program (Listing A) to find the minimu.docx
evonnehoggarth79783
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
fsenterprises
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
Srikanth
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
Srikanth
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
dhavalbl38
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
mohdjakirfb
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docx
adkinspaige22
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
arshiartpalace
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
ARCHANASTOREKOTA
 
2Part I1. Answer questions for the following graph, if .docx
2Part I1. Answer questions for the following graph, if .docx2Part I1. Answer questions for the following graph, if .docx
2Part I1. Answer questions for the following graph, if .docx
gilbertkpeters11344
 
Lab08Lab08.cppLab08Lab08.cpp.docx
Lab08Lab08.cppLab08Lab08.cpp.docxLab08Lab08.cppLab08Lab08.cpp.docx
Lab08Lab08.cppLab08Lab08.cpp.docx
DIPESH30
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
malavshah9013
 

Ähnlich wie Stack, queue and hashing (20)

Data structuresUsing java language and develop a prot.pdf
Data structuresUsing java language and develop a prot.pdfData structuresUsing java language and develop a prot.pdf
Data structuresUsing java language and develop a prot.pdf
 
6Modify the bfs.java program (Listing A) to find the minimu.docx
6Modify the bfs.java program (Listing  A) to find the minimu.docx6Modify the bfs.java program (Listing  A) to find the minimu.docx
6Modify the bfs.java program (Listing A) to find the minimu.docx
 
Were writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdfWere writing code for a project that dynamically allocates an arra.pdf
Were writing code for a project that dynamically allocates an arra.pdf
 
C aptitude questions
C aptitude questionsC aptitude questions
C aptitude questions
 
C - aptitude3
C - aptitude3C - aptitude3
C - aptitude3
 
For each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdfFor each task, submit your source java code file.(1) Objective Im.pdf
For each task, submit your source java code file.(1) Objective Im.pdf
 
Write a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdfWrite a program that converts an infix expression into an equivalent.pdf
Write a program that converts an infix expression into an equivalent.pdf
 
DS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL IntroductionDS & Algo 1 - C++ and STL Introduction
DS & Algo 1 - C++ and STL Introduction
 
Templates
TemplatesTemplates
Templates
 
@author Derek Harter @cwid 123 45 678 @class .docx
@author Derek Harter  @cwid   123 45 678  @class  .docx@author Derek Harter  @cwid   123 45 678  @class  .docx
@author Derek Harter @cwid 123 45 678 @class .docx
 
Unix executable buffer overflow
Unix executable buffer overflowUnix executable buffer overflow
Unix executable buffer overflow
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
StackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdfStackInterface An interface for the ADT stack. Do not modif.pdf
StackInterface An interface for the ADT stack. Do not modif.pdf
 
Implementing Software Machines in Go and C
Implementing Software Machines in Go and CImplementing Software Machines in Go and C
Implementing Software Machines in Go and C
 
2Part I1. Answer questions for the following graph, if .docx
2Part I1. Answer questions for the following graph, if .docx2Part I1. Answer questions for the following graph, if .docx
2Part I1. Answer questions for the following graph, if .docx
 
Oop 1
Oop 1Oop 1
Oop 1
 
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx  Find an LCS of X =  and Y =   Show the c and b table.  Attach File  .docx
Find an LCS of X = and Y = Show the c and b table. Attach File .docx
 
Implementing Software Machines in C and Go
Implementing Software Machines in C and GoImplementing Software Machines in C and Go
Implementing Software Machines in C and Go
 
Lab08Lab08.cppLab08Lab08.cpp.docx
Lab08Lab08.cppLab08Lab08.cpp.docxLab08Lab08.cppLab08Lab08.cpp.docx
Lab08Lab08.cppLab08Lab08.cpp.docx
 
Create a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdfCreate a JAVA program that performs file IO and database interaction.pdf
Create a JAVA program that performs file IO and database interaction.pdf
 

Kürzlich hochgeladen

Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Kürzlich hochgeladen (20)

[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 

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 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.
  • 3. Stack Model  Input to a stack is by push  Access is by top  Deletion is by pop
  • 4. Important stack applicationsImportant stack 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 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
  • 7. 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; }} //---------------------------------//---------------------------------
  • 8. 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); }} }}
  • 9. 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(" "); }}
  • 10. 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; }} //---------------------------------//---------------------------------
  • 11. 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); }}
  • 12. 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
  • 13. 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
  • 14. 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 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
  • 15. 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; } //---------------------------------} //--------------------------------- } //} //
  • 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 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.
  • 18. 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()
  • 19.
  • 20.
  • 21.  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.
  • 22. 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
  • 23. 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; }
  • 24. 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; }
  • 25. 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(); } }
  • 26. 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.
  • 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 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.
  • 29. 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; }
  • 30. 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()
  • 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 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
  • 33. 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.
  • 34. 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.
  • 35. 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.
  • 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 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
  • 39.  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.
  • 40.  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
  • 41.  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.