list stack queue eng
TRANSCRIPT
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 1/90
04/17/12 1
List, Stack,Queue
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 2/90
04/17/12 2
List
It is about putting things in a
sequence.
Example: A1,A2,A3,…,An
first last
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 3/90
04/17/12 3
What can we do
with a list Find – find a specified member. Insert – insert a new member at a specified
position.
findKth – return the kth element. Remove – remove a specified element
from list. Head – return the first member. Tail – return the list without its first member. Append – combine 2 lists.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 4/90
04/17/12 4
What if wecreate a list from
an array? Do not forget that an array needs us to specify itslength.
Find -> O(n)
Because we need to search from the firstelement of the list. findKth –O(1)
We can use index to find the kth elementdirectly.
Insert and remove may take a long timeBecause all members may be shifted.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 5/90
04/17/12 5
Linked list
Find -> O(n)
because we still need to start at the
biginning of the list.
findKth(i) -> O(i)
Because we cant use array index any
more.
A1 A3A2
node
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 6/90
04/17/12 6
Linked list
(cont.) Deletion is easier (no need to shift members)We only need to point reference over to the
next node.
A1 A3A2The original list
When A2 is removed.A1 A3A2
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 7/90
04/17/12 7
Linked list (cont
2.) Insertion is also similar.
The original list
After inserting x between A2 and A3.
A1 A3A2
x
A1 A3A2
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 8/90
04/17/12 8
Insert -> a small
problem Inserting the first member is different from
inserting others.No other node pointing to x.
Need the former A1 reference to point to x.
A1 A3A2
x
The code needs to be different from other insertions.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 10/90
04/17/12 10
Code:node
class ListNode
{// Constructors
ListNode( Object theElement )
{
this( theElement, null );
}
ListNode( Object theElement, ListNode n ){
element = theElement;
next = n;
}
theElement
theElement Point
to n.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 11/90
04/17/12 11
// Friendly data; accessible byother package routines
Object element;
ListNode next;
}
Instance variables
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 12/90
04/17/12 12
List iterator Is an object pointing to a node we are
interested in. Why do we have to write this class separate
from list?We can keep an interested node in our list
anyway, right?
It’s because If we use iterator, we can keep a general form
of list separate from any interested node.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 13/90
04/17/12 13
Code:iterator
public class LinkedListItr
{ListNode current; //interested position
/**
* @param theNode any node in the list*/
LinkedListItr( ListNode theNode )
{current = theNode;
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 14/90
04/17/12 14
/** see if current has passed the last element of the list.
* @return true if current is null
*/
public boolean isPastEnd( ){
return current == null;
}
/**
* @return item stored in current, or null if
* current is not in a list.
*/public Object retrieve( )
{
return isPastEnd( ) ? null : current.element;
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 15/90
04/17/12 15
/**
* move current to the next position in the list.
* If current is null, do nothing.
*/
public void advance( )
{
if( !isPastEnd( ) )current = current.next;
}
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 16/90
04/17/12 16
Code: linked list
public class LinkedList{
private ListNode header;
public LinkedList( )
{header = new ListNode( null );
}
public boolean isEmpty( ){
return header.next == null;
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 17/90
04/17/12 17
/** make the list empty.*/
public void makeEmpty( )
{
header.next = null;
}
/**
* return iterator that points to the header node.
*/
public LinkedListItr zeroth( )
{
return new LinkedListItr( header );
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 18/90
04/17/12 18
/* return iterator that points to the node next to header (can be null if the list is empty.)*/
public LinkedListItr first( )
{return new LinkedListItr( header.next );
}
/** insert a new node following the position pointed to by p.* @param x item to be in the new node.
* @param p iterator of the position before the new node.
*/
public void insert( Object x, LinkedListItr p ){
if( p != null && p.current != null )
p.current.next = new ListNode( x, p.current.next );
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 19/90
04/17/12 19
/**
* @param x object that we want to find.
* @return iterator that points to the first node that has x.
*If x is not in the list, the iterator points to null.*
*/
public LinkedListItr find( Object x )
{/* 1*/ ListNode itr = header.next;
/* 2*/ while( itr != null && !itr.element.equals( x ) )
/* 3*/ itr = itr.next;
/* 4*/ return new LinkedListItr( itr );
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 20/90
04/17/12 20
/**
* return iterator that points to a node before the first• *node that has x. If there is no x in the list, return iterator
*that points to the last node in the list.*/
public LinkedListItr findPrevious( Object x )
{
/* 1*/ ListNode itr = header;
/* 2*/ while( itr.next != null && !itr.next.element.equals( x ) )
/* 3*/ itr = itr.next;
/* 4*/ return new LinkedListItr( itr );
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 21/90
04/17/12 21
/**
* remove the first node with x from the list.
* @param x is the item to be removed from the list.
*/public void remove( Object x )
{
LinkedListItr p = findPrevious( x );
if( p.current.next != null ) //mean x is found because
// p is not the last member.
p.current.next = p.current.next.next;//move reference
//over x
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 22/90
04/17/12 22
public static void printList( LinkedList theList )
{
if( theList.isEmpty( ) )System.out.print( "Empty list" );
else
{
LinkedListItr itr = theList.first( );for( ; !itr.isPastEnd( ); itr.advance( ) )
System.out.print( itr.retrieve( ) + " " );
}
System.out.println( );
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 23/90
04/17/12 23
Doubly linked list
Node has extra instance variable: Previous : point to the node in front. This works
the same way as next, but pointing in a different
direction.We can search both ways.
Additional time to change pointers.
A1 A3A2
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 24/90
04/17/12 24
Insert: doubly linked
list
A1 A3A2
X
1
newnode
32
4
P
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 25/90
04/17/12 25
Remove: doubly
linked list
A1 A3A2
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 26/90
04/17/12 26
Circular Linked
list
Last node points to the first node.
no dummy node needed.
We can even make it into a doublylinked list.
A1 A3A2
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 27/90
04/17/12 27
linked list example Let us want to store a polynomial
We can use array, using index i to
store the coefficient of
i
n
i
i xa∑
=0
i x
a0 a1 ……a2
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 28/90
04/17/12 28
Using array to storepolynomial
The answer comes from the addition of
corresponding slots, as shown.
a0 a1 ……a2
a0 a1 ……a2
When adding polynomials
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 29/90
04/17/12 29
Using array to storepolynomial (2)
Each slot multiplies every slot of the other
polynomial, then all results are added. If there are many terms with 0 coefficient,there will be so many multiplication with 0.Waste of time.
multiplying two polynomiala0 a1 ……a2
a0 a1 ……a2
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 30/90
04/17/12 30
use linked list
instead Reduce the number of 0. Save space.
Example: 5x75+11x125+8
5 811
header
75 125 0
coefficient Power of x
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 31/90
04/17/12 31
Skip list A node can have more than one “next” pointers. The extra pointers point to other parts of the list.
2 6
8
5
122
15
In this example, every node has a pointer to next. A node in a position that is divisible by two will also
have a pointer pointing to the next node with that
quality.
Same for a node in a position divisible by four.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 32/90
04/17/12 32
Skip list problem Inserting and removing an element will cause all
pointers structure to be changed. Too hard to do.
Usually only the number of pointers for each levelis enforced. Example: a 20 node list.
Level 0 –> 20 nodes
Level 1– > 10 nodes Level 2 -> 5 nodes Level 3 -> 2 nodes
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 33/90
04/17/12 33
Skip list problem
(cont) The number of nodes in the example: Level 3 -> 2 nodes
Level 2 -> 5-2 = 3 nodes
Level 1 -> 10-2-3 = 5 nodes Level 0 -> 20-5-3-2 = 10 nodes
When adding a new node, random a number
between 1 and 20. 1 to 10 -> add the node with link level 0.
11 to 15 -> add the node with link level 1.
And so on.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 34/90
04/17/12 34
Self-Organizing
List Put the data just viewed in front of the list, or Swap the node just viewed with a node in front, or Putting elements according to access frequency,
or Use a specific ordering scheme, such as
alphabetically ordered.Good for searching.
If we cannot find an element within a certain number of steps, we will know that the element is not in a list.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 35/90
04/17/12 35
Self-Organizing
List(cont.) Adam Drozdek (he has a book on data structure)
found that
Putting the most recently viewed data in front of alist yields the same speed as ordering the list by
data access frequency.
Faster than
swapping the node just viewed with a node in front.Using a specific ordering scheme.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 36/90
04/17/12 36
Multilist or Sparce
Matrix Example: data of all students and all subjectstaught by our university. We must be able to:Find all subjects a particular student is taking.
Find all students enroll in a particular subject. We can use a 2D array to create a table of
students and subjects.But there will be lots of empty spaces.
A medical student and an engineering studentsurely enroll in different subjects.
We can fix this problem by making a 2D list.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 37/90
04/17/12 37
Subj
1
2
3
32Student 1
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 38/90
04/17/12 38
graphC
B
A
DE
A
B
C
D
E
A B C D E
Sparce tableA
B
B
E
A
C
B
D
E
C
Node directory
t k
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 39/90
04/17/12 39
stack Are divided into levels.
We can only insert andremove things one way.(LIFO = last in, first out)
What can we do:
Push – put an object atthe top.
Pop – remove the topmost element.
Top – return the topelement withoutremoving anything.
A
BC
ฏ
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 40/90
04/17/12 40
Making a stack from list
Push = insert new object next toheader.
Pop = remove object next to header.If the list is originally empty, we canDo nothing, or
throw exception. Top = return an element in the node
next to header.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 41/90
04/17/12 41
Stack code Modified from linked listFor simplicity, we do not have a header in
this example.
We can make a stack even though we donot have header.
public class StackFromLinkedList {
private ListNode top;
public StackFromLinkedList( ){
top = null;
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 42/90
04/17/12 42
/**
* @return always return false.
*/
public boolean isFull( ){
return false;
}
/**
* @return true if stack is empty, otherwise return false.
*/
public boolean isEmpty( ){
return top == null;
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 43/90
04/17/12 43
public void makeEmpty( )
{
top = null;
}
/**
* @return top of stack, or null if empty.
*/public Object top( )
{
if( isEmpty( ) )
return null;return top.element;
}
Top does not change stack.
Can choose to throw exception.
/**
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 44/90
04/17/12 44
/**
* remove element on top of stack.
* @exception Underflow if stack is empty.
*/
public void pop( ) throws Underflow
{
if( isEmpty( ) )throw new Underflow( );
top = top.next;
}
Just moving the pointer over.
Can choose to do nothing.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 45/90
04/17/12 45
/**
* top() and pop()
* @return popped item, or null if the stack is empty.
*/
public Object topAndPop( )
{
if( isEmpty( ) )return null;
Object topItem = top.element;
top = top.next;
return topItem;
}
Can choose to throw exception.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 46/90
04/17/12 46
/**
* put new element on top of stack.
* @param x element we want to put in stack.*/
public void push( Object x )
{top = new ListNode( x, top );
}
Old node New node
New top points to old top.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 47/90
04/17/12 47
Stack weakness
When popped out, an element
disappear forever.
We need to keep elements in extra
variables, or another stack.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 48/90
04/17/12 48
Creating stack with
array Do not forget that we need to specify
array size.
Let a stack havearrayBody
topIndex – index of the top element.
(-1 if the stack is empty.)
Code: stack made
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 49/90
04/17/12 49
Code: stack madefrom array
public class StackFromArray {
private Object [ ] arrayBody;
private int topIndex;
static final int DEFAULT_CAPACITY = 10;
public StackFromArray( )
{
this( DEFAULT_CAPACITY );
}
/**
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 50/90
04/17/12 50
/**
* create a stack, specifying its capacity.
* @param capacity number of elements the* stack can hold.
*/
public StackFromArray( int capacity )
{
arrayBody = new Object[ capacity ];
topIndex = -1;
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 51/90
04/17/12 51
public boolean isEmpty( )
{
return topIndex == -1;
}
public boolean isFull( )
{return topIndex == arrayBody.length - 1;
}
public void makeEmpty( )
{
topIndex = -1;
}
public Object top( )
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 52/90
04/17/12 52
p j p( )
{
if( isEmpty( ) )
return null;
return arrayBody[ topIndex ];}
/**
* remove top element from stack.
* @exception Underflow if the stack is empty.
*/
public void pop( ) throws Underflow
{
if( isEmpty( ) )
throw new Underflow( );
arrayBody[ topIndex-- ] = null;
}
Set to null
Then move index
Can choose to throw exception.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 53/90
04/17/12 53
/**
* Remove top element from stack and return that element.
* @return object on top of stack or null if the stack is
empty.
*/
public Object topAndPop( ){
if( isEmpty( ) )
return null;
Object topItem = top( );arrayBody[ topIndex- - ] = null;
return topItem;
}
Can choose to throw exception.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 54/90
04/17/12 54
/**
* put x in stack if the stack is not full
* @param x object to put on top of tack.* @exception Overflow if the stack is full.
*/public void push( Object x ) throws Overflow
{
if( isFull( ) )
throw new Overflow( );
arrayBody[ ++topIndex ] = x;
}
}move index and then put x in.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 56/90
04/17/12 56
Using stack (2)
Postfix expression (reverse polish) [7+(8*9)+5]*10 = 7 8 9 * 5 + + 10 *
We can use stack to evaluate a postfix expression:Read a number -> push to stack.
Read an operator -> pop numbers in the stack and
use the operator on the numbers.
7
Example: reading
the first three
numbers.
89
Wh di *
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 57/90
04/17/12 57
7
When reading *
8
9
Pop two numbers, multiply.put the result back
in stack.
7
72
Then read 5 in normally.
7
72
5
read +, pop the top two and add them.
7
72
5
7
77
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 58/90
04/17/12 58
7
77
The same for the second +.
84
Reading 10 normally.
84
10
When reading *, pop the top two and * them.
84
10
840answer
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 59/90
04/17/12 59
Using stack (3) Change infix to postfix
Operand -> output it right away.
operator -> keep it on stack.
Keep “(“ on stack too.When reading “)”-> pop and output continuously
until we find “)”.
Let’s see an example.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 60/90
04/17/12 60
a+b*c+(d*e+f)*g
+
read a,+,b -> put a and b in output. Put + on top of stack.
a b
read * and read c -> put * on top of stack. Put c in output.
+ a b c
*
read + -> must pop equal (or more) priority operator out tooutput, before we push the + on top of stack.
+ a b c * +
new
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 61/90
04/17/12 61
read “(“ and d -> put “(“ into stack, waiting for “)”. We put d to output.
+ a b c * + d
(
Then, reading * and e.
+ a b c * + d e(
*
Next, + and f
+ a b c * + d e * f
(
*
+ pushed in after popping equal (or more)
priority operators.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 62/90
04/17/12 62
Next is “)” -> pop everything up to “(“.
+ a b c * + d e * f +
(
+
Pop
Next are * and g -> push * into stack. Put g to output.
+ a b c * + d e * f + g
*
No more input, we pop everything on stack to output.
a b c * + d e * f + g * +
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 63/90
04/17/12 63
Using stack (4) Change infix to prefix If reading a number from input:
Put that number in our operand stack.
If reading an operator:1. If operator stack is empty, push it in.
2. If the operator is “(“, push it in the operator
stack.3. If the operator has more priority than the
operator on top of the operator stack, push it in
the operator stack.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 64/90
04/17/12 64
4. If the operator has equal or less prioritythan the operator on top of the stack: Pop an operator from the operator stack. Pop operands used by popped operators
from the operand stack.
Put the operator first, followed by theoperands. The latest one is put first. Put the result in the operand stack.
If the operator is “)”, or if we cannot
read from input any further, follow step4 until the top of the operand stackbecomes “(“. Then pop that “(“ out.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 65/90
04/17/12 65
–b+sqrt(b*x – d*a*c)/(e*a)First, read – ,b. put each one in its stack.
b -
Operand stack Operator stack
read +. Because + has equal priority to – (which is on the
operator stack), we need to pop – out and put - with its
operand.
-b +
Then read sqrt and “(“. Sqrt is just like a method. Therefore it has
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 66/90
04/17/12 66
more priority than other operations. We push it in stack. We also put
“(“ in stack.
-b (
sqrt
+
Next are b, *, x. we can push all of them.
x
(
sqrt
+
b
-b
*
N i B i l i h * * d
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 67/90
04/17/12 67
Next is –. Because – is less important than *, we must pop * out and
work with it.
*bx (
sqrt
+
-b -
Then read d, *, a. * is more important than -, therefore we can push
it in stack. We can also push d and a.
a
(sqrt
+
d -*bx-b
*
N t d * Thi ti th * i t f th t k W th
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 68/90
04/17/12 68
Next we read *. This time another * is on top of the stack. We then
must pop stack and push result back.
*da
(
sqrt
+
-*bx
-b
* (new)
Then read c and push it (no drawing this time).
Then read “)” Pop stack and arrange operators and operands until
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 69/90
04/17/12 69
Then read ) . Pop stack and arrange operators and operands until
we find “(“. Then remove “(“.
(sqrt
+
-*bx-b
**dac
Then pop – out.
sqrt
+-b
-*bx**da
c
Then read / -> less priority than sqrt. Therefore we pop sqrt to work.
/+-b
sqrt -*bx**dac
Th d ( d P h th
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 70/90
04/17/12 70
Then read ( and e. Push them.
/+-b
sqrt -*bx**dac
e (
Then read * and a. Push them.
/+-bsqrt -*bx**dac
e (
a *
Then read “)” Pop * to work and remove the bracket
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 71/90
04/17/12 71
Then read ) . Pop to work and remove the bracket.
/
+
-bsqrt -
*bx**dac
*ea
Now we finish input reading. We then pop operators to work with
operands. First, pop /.
+
-b
/ sqrt -*bx**dac*ea
Then pop +. The overall result is on the operand stack.
+ -b/ sqrt -*bx**dac*ea
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 72/90
04/17/12 72
Using stack (5) Store method call data
Local variables of a method must be stored
independently, to prevent name clash with variables
in other methods.Must store the return point of a method.
We can create a stack to store a method data.activation record or stack frame
h d1(){
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 73/90
04/17/12 73
method1(){
method2();
}
method2(){
method3();
}
method3(){
…
}
main (){
method1();
}
method1’s info
method2’s info
method3’s info
top
Careful with
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 74/90
04/17/12 74
Careful withmethod
There is a form of recursion which wastes stack. It is called tail recursion.
recursive call on the last line of a method.
myAlgo(ListNode p){
if (p == null)
return;
//do something
myAlgo(p.next);
}
For each call, it just call another method without. Each
stack will not contain any data- a waste.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 75/90
04/17/12 75
fixing tail recursion Let compiler handle it or Write a loop instead.
myAlgo(ListNode p){
while(true){if (p == null)
return;
//do something
p = p.next;}
}
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 76/90
04/17/12 76
Queue It is a list. But we can put things in at the back only (enqueue). And we
can remove things from the front only (dequeue).
We can implement queue using A modified list
array
8 4 3 6 7
front back
Enqueue and dequeue
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 77/90
04/17/12 77
Enqueue and dequeuefor queue built from
array (1) enqueue(x) size++
back++ theArray[back] = x
dequeue() size- -
front++
Enqueue and dequeue
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 78/90
04/17/12 78
Enqueue and dequeuefor queue built from
array (2)Be careful.
Fix it by making the index go round.
8 4 3 6 7 10
front back
Cannot Enqueue even though there are spaces at the front.
9 8 4 3 6 7 10
front back
Enqueue and dequeue
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 79/90
04/17/12 79
Enqueue and dequeuefor queue built from
array (3) when back = front-1, a queue can be either empty
or full. Therefore we have size.
Fix error when Adding an item to a full queue.
Dequeue an empty queue.
public class QueueArray{
i t Obj t [ ] th A
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 80/90
04/17/12 80
private Object [ ] theArray;
private int size;
private int front;
private int back;
static final int DEFAULT_CAPACITY = 10;
public QueueArray( )
{this( DEFAULT_CAPACITY );
}
public QueueArray( int capacity ){
theArray = new Object[ capacity ];
makeEmpty( );
}
public boolean isEmpty( )
{
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 81/90
04/17/12 81
{
return size == 0;
}
public boolean isFull( )
{
return size == theArray.length;
}
public void makeEmpty( )
{
size = 0;front = 0;
back = -1;
}
public Object getFront( ) {
if( i E t ( ) )
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 82/90
04/17/12 82
if( isEmpty( ) )
return null;
return theArray[ front ];
}
/*return an item at the front of the queue, delete that item. Return nullif the queue is empty.*/
public Object dequeue( ){
if( isEmpty( ) )return null;
size--;
Object frontItem = theArray[ front ];
theArray[ front ] = null;
front = increment( front );
return frontItem;
}
Can throw exception.
Can throw exception.
/**
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 83/90
04/17/12 83
* put x at the back of queue.
* @param x object to be put in the queue.
* @exception Overflow if the queue is full.*/
public void enqueue( Object x ) throws Overflow
{
if( isFull( ) )throw new Overflow( );
back = increment( back );
theArray[ back ] = x;
size++;}
/**
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 84/90
04/17/12 84
/**
* increment array index, allowing the index to go round*the array.
* @param x array index, must be a legal index.
* @return x+1, or 0 if x is the at the back of the array.
*/
private int increment( int x )
{
if( ++x == theArray.length )
x = 0;
return x;
}
double ended queue
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 85/90
04/17/12 85
double-ended queue insertFirst(Object o): put o at the front.
insertLast(Object o): put o at the back.
removeFirst(): remove the front element.
removeLast(): remove the last element.
first(): return the first element.
last(): return the last element.
size(): return the queue size.
isEmpty(): test if the queue is empty.
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 86/90
04/17/12 86
stack double-ended queue
size() size()
isEmpty() isEmpty()
top() last()
push(x) insertLast(x)
pop() removeLast()
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 87/90
04/17/12 87
queue double-ended queue
size() size()
isEmpty() isEmpty()
getFront() first()
enqueue(x) insertLast(x)
dequeue() removeFirst()
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 88/90
04/17/12 88
Queue usage printer
Jobs waiting at a printer can jump queue according
to job priority.
Supermarket queue simulation.Used queue simulation to decide whether to increase
service size.
Call center queue.
Supermarket
8/4/2019 List Stack Queue ENG
http://slidepdf.com/reader/full/list-stack-queue-eng 89/90
04/17/12 89
We can find an average waiting time.
queue
paying
pqueue
If customer come at time -> 30, 40, 60,110, 170