Sei sulla pagina 1di 60

Stack

Department of CE

Content
Stack Stack operation
Push Pop

Stack Representation
Array Linked list

Applications
Department of CE

Stack as an ADT(Abstract Data Type): A Stack is an ordered list in which all insertions and deletions are made at one end, called the top. Given a stack S=(a[1],a[2],.......a[n]) then we say that a[1] is the bottommost element and element a[i] is on top of element a[i1], 1<i<=n.

The restrictions on a stack imply that if the elements A,B,C,D,E are added to the stack, in that order, then the first element to be removed/deleted must be E. Equivalently we say that the last element to be inserted into the stack will be the first to be removed. For this reason stacks are sometimes referred to as Last In First Out (LIFO) lists.

ADT Operations: Push(item) : pushes an item on the stack Pop() : removes the first item from the stack Top() : returns the first item from the stack isEmpty() : returns true if the stack is Empty isFull() : returns true if the stack is Full.

Stack Operation

Array representation of stack


Stacks are represented in the computer memory using array structure or linked list structure. The figure shows the representation using an array namely STACK[N] N is the size of the stack and top is a pointer variable which holds the index value of the topmost element in the stack. If the value of top is zero or NULL, the stack is said to be empty. If the value of top is N, then the stack is said to be full.

Department of CE

Figure
N

N-1
N-2 N-3 . . . .

6 5 TOP - 4 3 2 1 93 58 7
Department of CE

22

Department of CE

Implementation of Stack using Arrays: Algorithm Push(item): //Stack, top and n are a global variable //n is the size of the array //Push on the top of the Stack Begin if isFull()=true then Stack is Full Else Begin top <- top+1; Stack[top] <- item; End if //end if End

Department of CE

Algorithm Pop(): //Stack, top and n are a global variable //n is the size of the array //delete from the top of Stack and put in item Begin
if isEmpty()=true then Stack is Empty Else Begin Item <- Stack[top]; top <- top-1; End if

//end if

End

//end of Pop()

Algorithm Top(): //Stack, top and n are a global variable //n is the size of the array Begin Return Stack[top]; End //end of Top()

Algorithm isEmpty(): //Stack, top and n are a global variable //n is the size of the array Begin If top=-1 then return true; else return false; End if //end of if End //end of isEmpty()

Algorithm isFull(): //Stack, top and n are a global variable //n is the size of the array Begin If top=n then return true; else return false; End if //end of if End //end of isEmpty()
Department of CE

Linked list representation of stack


This type of representation has more advantages than representing stacks using arrays. They are

It is not necessary to specify the number of elements to be stored


in a stack during its declaration. Insertions and deletions can be handled easily and efficiently. Linked list representation of stacks can grow and shrink in size without wasting the memory space, depending upon the insertion and deletion that occurs in the list. Multiple stacks can be represented efficiently using a chain for each stack.
Department of CE

Stack Using Linked List CONCEPT : LIFO Inserting an element from front and deleting an element from front is nothing but STACK

Compiled By JVGorabal Asst Prof CSE Dept

Push item 30
S T

A C K

L I N K E D L I S T

top
3000 30 Null

Compiled By JVGorabal Asst Prof CSE Dept

S T A C 2000 K

Push item 20
L I N K E D L I S T

top
20 3000

3000

30

Null

Compiled By JVGorabal Asst Prof CSE Dept

Push item 10

top
S T A C 2000 20 3000 1000 10 2000 L I N K E D L I S T

3000

30

Null

Compiled By JVGorabal Asst Prof CSE Dept

POP

10

S T A C 2000 20 3000

top

L I N K E D L I S T

3000

30

Null

Compiled By JVGorabal Asst Prof CSE Dept

POP

20

S T A C

top
3000 30 Null

L I N K E D L I S T

Compiled By JVGorabal Asst Prof CSE Dept

POP

30

S T A C

STACK EMPTY

L I N K E D L I S T

Compiled By JVGorabal Asst Prof CSE Dept

Application of Stack - Evaluating Postfix Expression


(5+9)*2+6*5 An ordinary arithmetical expression like the above is called infix-expression -- binary operators appear in between their operands. The order of operations evaluation is determined by the precedence rules and parenthesis.

When an evaluation order is desired that is different from that provided by the precedence, parentheses are used to override precedence rules.
Department of CE

Application of Stack - Evaluating Postfix Expression


Expressions can also be represented using postfix notation - where an operator comes after its two operands.
The advantage of postfix notation is that the order of operation evaluation is unique without the need for precedence rules or parenthesis.
Infix 16 / 2 (2 + 14)* 5 2 + 14 * 5 (6 2) * (5 + 4) Postfix 16 2 / 2 14 + 5 * 2 14 5 * + 6 2 - 5 4 +*

Application of Stack - Evaluating Postfix Expression


The following algorithm uses a stack to evaluate a postfix expressions. Start with an empty stack for (each item in the expression) { if (the item is a number) Push the number onto the stack else if (the item is an operator){ Pop two operands from the stack Apply the operator to the operands Push the result onto the stack } } Pop the only one number from the stack thats the result of the evaluation

Application of Stack - Evaluating Postfix Expression


Example: Consider the postfix expression, 2 10 + 9 6 - /, which is (2 + 10) / (9 - 6) in infix, the result of which is 12 / 3 = 4. The following is a trace of the postfix evaluation algorithm for the above.

END

Department of CE

Queue Queue operation


Push Pop

Queue Representation
Array Linked list

Applications
Department of CE

Queue as an ADT(Abstract Data Type): Queue is basically a finite sequence of elements of same type. It is a linear structure in which additions and deletions takes place at different ends. The end at which new elements are added is called the rear, and the end from which elements are deleted is called the front. Example:

So a queue follows First-In-First-Out (FIFO) pattern of sequence. The FIFO property causes to operate like a line of people waiting to get their movie tickets for a show. We call the insert operation on a queue Enqueue, and we call the delete operation Dequeue. When an element is enqueued, it takes place at the rear end of the queue, the element dequeued is always the one at the front end of the queue.

ADT Operations: Create(q) : which creates q as an empty Queue Enqueue(x,q) : which adds the element x to the rear of a queue and returns the new queue Dequeue(q) : which removes the first element from the queue q and returns the resulting queue Front(q) : which returns the first element of queue q IsEmpty(q) : which returns true if q is empty, else False.

Department of CE

Implementation of Queue using Arrays: Algorithm Enqueue(x): // Q, rear, front and n are global variables // n is the size of the array Begin
if rear = n then Queue is Full else Begin rear<- rear + 1 Q[rear] <- x End if

// end if

End

// end of Enqueue(x)

Algorithm Dequeue(q): // delete from the front of q and put it into item // Q, rear, front and n are global variables // n is the size of the array 1. Begin 2. if front = rear then 3. Queue is Empty 4. else begin 5. front <- front+1 6. item <- Q[front] 7. End if 8. End

// end if // end of Dequeue(q)

Major Problem: Queue Migration is a problem commonly found in queues when implemented using arrays. As we remove the items from the queue, the queue migrates to one end and the other end remains empty. When we try to insert an element in the queue though there are empty spaces in the queue, it gives a message saying that the Queue is full.

Fig2: Eg. Queue Migration

Fig3: Eg. Queue Migration Here in this example, Fig2, The maximum size of the array is 4 and four elements 0,1,2,3 are inserted in the queue. when i delete two elements from it, the queue changes like example Fig3. Now I insert a number 4 in the queue, it returns a message Queue is Full.

Circular Queue: As the name suggests, this queue is not straight but circular, it looks like this

Fig: Eg. Circular Queue In this Circular queue, once the queue is full, the first element of the queue becomes the rear most element of the queue. Initially when the queue is empty front and rear values are 0 and -1. Queue has got null values to all its elements. Every time when we add an element to the queue, the rear value increments by one till the time it reaches the upper limit of the queue after which it starts all over again from 0. Here the condition front>rear wont work.

For an element to be enqueued, Algorithm CircEnqueue(q,x): // add item(x) to the queue q // q,front,rear,n are global variables // n is the size of the array 1. begin
2. if (q.front = q.(rear+1)mod n) then 3. Queue is FULL 4. else begin 5. q.rear = q.(rear+1) mod n 6. q.item[rear] = x 7. end //end if

8. end // end of CircEnqueue

For an element to be dequeued, Algorithm CircDequeue(q,x) // delete from the front of q 1. begin 2. if (q.front = q.(rear+1)mod n) then 3. Queue is EMPTY 4. else begin 5. q.front = q.(front+1) mod n 6. end //end if 7. end // end of CircDequeue

Here the condition for both Full and Empty is the same (front = (rear+1) % n)

From the above condition, we cant determine whether it is Full or Empty condition We can avoid this by keeping a counter variable (size) to check for Full and Empty conditions. We can increment size by one while inserting an element in a queue and decrement size by one while deleting an element from the queue. By this method, complexity is doubled. The alternative for this is
ADT Queue of Circular array with one empty position We keep a position before the front as always empty or NULL and never allow any element to be inserted at that position.The initial conditions will be rear = 0 and front = 1.

Now, the condition to check for Empty is front = =-1 The condition to check for Full is front = (rear+1) % n In array based implementation, all opertions take O(1) time.

Fig5: Eg. Circular Queue

Insert Circular ( ): Description: Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear elements of the QUEUE. ITEM is the value to be inserted. 1. 2. 3. 4. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then Print: Overflow Else If (REAR == 0) Then [Check if QUEUE is empty] (a) Set FRONT = 1 (b) Set REAR = 1 5. Else If (REAR == N) Then [If REAR reaches end if QUEUE] 6. Set REAR = 1 7. Else 8. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If] 9. Set QUEUE[REAR] = ITEM 10. Print: ITEM inserted [End of Step 1 If] 11. Exit

Implementation Q using linked Lits

Inserting an Element from the rear and deleting An element from the front is nothing but Q

Compiled By JVGorabal Asst Prof CSE Dept

Inserting 20
temp

20

NULL

Front=null Front=rear=temp

Compiled By JVGorabal Asst Prof CSE Dept

Inserting 20
front/rear

20

NULL

Compiled By JVGorabal Asst Prof CSE Dept

Inserting 30
front/rear temp

20

NULL

30

null

2000

rear->link=temp

Compiled By JVGorabal Asst Prof CSE Dept

Inserting 30
front rear

20

2000

30

null

1000 rear->link=temp rear=temp

2000

Compiled By JVGorabal Asst Prof CSE Dept

Inserting 40
front rear

20

2000

30

null

40

Null

1000 rear->link=temp rear=temp

2000

Compiled By JVGorabal Asst Prof CSE Dept

Inserting 40
front rear

20

2000

30

3000

40

Null

1000 rear->link=temp rear=temp

2000

3000

Compiled By JVGorabal Asst Prof CSE Dept

Delete Operation
Deleting 20 front rear

20

2000

30

3000

40

Null

1000 temp=front front=front->link free(temp)

2000

3000

Deleting 30
front rear

30

3000

40

Null

2000

3000

Compiled By JVGorabal Asst Prof CSE Dept

Deleting 40

front

rear

40

Null

3000

Compiled By JVGorabal Asst Prof CSE Dept

Q Empty

ALGORITHM: insert(cqueue_arr[MAX],rear,front,add_item) 1. Initialize front=rear=-1 2. [check Overflow condition] if front == (rear + 1) % MAX then print: OVERFLOW & exit. 3. if front== -1 then Set front=rear=0 else Set rear=(rear +1) % MAX 4. cqueue_arr[rear]=add_item 5. Exit
Department of CE

delete(rear,front,MAX) 1. if front=-1 then print: UNDERFLOW & exit. 2. if front==rear then Set front=rear=-1 else Set front=(front + 1) % MAX 3. Exit
Department of CE

Stack
Properties
Elements removed in opposite order of insertion Last-in, First-out (LIFO) Must track position of Top (last element added)

Stack operations
Push Pop = add element (to top) = remove element (from top)

Stack Implementations
Linked list
Add / remove from head of list

Array
Increment / decrement Top pointer after push / pop
X Y Z Top

Stack Applications
Run-time procedure information

Arithmetic computations
Postfix notation

Simplified instruction set


Java bytecode

Queue
Properties
Elements removed in order of insertion First-in, First-out (FIFO) Must track Front (first in) and Back (last in)

Queue operations
Enqueue = add element (to back)

Queue Implementations
Linked list
Add to tail (Back) of list Remove from head (Front) of list

Array Circular array

Queue Array
Store queue as elements in array Problem
Queue contents move (inchworm effect)

As result, can not add to back of queue, even though queue is not full

Queue Circular Array


Circular array (ring)
q[ 0 ] follows q[ MAX 1 ] Index using q[ i % MAX ]

Problem
Detecting difference between empty and nonempty queue

Queue Circular Array


Approach 1 Keep Front at first in Keep Back at last in

Problem Empty queue identical to queue with 1 element

Queue Circular Array Approach 2


Keep Front at first in Keep Back at last in 1

Problem Empty queue identical to full queue

Inherent problem for queue of size N

Queue Circular Array

Only N possible (Front Back) pointer locations N+1 possible queue configurations
Queue with 0, 1, N elements

Solutions
Maintain additional state information
Use state to recognize empty / full queue Examples
Record Size Record QueueEmpty flag

Leave empty element in queue Store marker in queue

1. Display the elements of a singly linked list in the reverse order. (Use a stack) 2. Reverse a Queue using a stack. 3. Write function for ADDQ and DELQ on a queue using dynamic memory allocation method. 17. Write a menu driven program in C to implement Queue using a singly linked list 1. Add 2. Delete 3. Exit

Potrebbero piacerti anche