0% found this document useful (0 votes)
13 views

Chapter-6 STACKSds

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Chapter-6 STACKSds

Uploaded by

vinaydarling063
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 30

Chapter - 6

STACKS
The linear lists and linear arrays allow inserting and deleting elements at any place in the list i.e.
at the beginning, at the end, or in the middle. There are certain frequent situations when one
wants to restrict insertions and deletions so that they can take place only at the beginning or at
the end of the list, not in the middle. One of the data structures that are useful in such situations
is a stack.

STACK
A stack is a linear list of elements in which an element may be inserted or deleted only at one
end, called the top of the stack. This means, in particular, that elements are removed from a stack
in the reverse order of that in which they were inserted into the stack.

Stacks are also called last in – first out (LIFO) lists. Other names used for stacks are “piles” and
“push-down lists”.

Examples
Three every day examples of stack: a stack of coins, stack of books and computer stack are
shown in the figure below.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 1


Representation of stack in memory
Stacks may be represented in the computer in various ways, usually by means of a

1) Arrays

2) Single-linked lists

1) Implementation of Stack using Arrays

A Stack contains an ordered list of elements and an array is also used to store ordered list of
elements. Hence it would be very easy to manage a stack using an array. However, the problem
with an array is that we are required to declare the size of the array before using it in a program.
Therefore the size of the stack would be fixed.

2) Implementation of Stack using single linked lists

When a stack is implemented using arrays, it suffers from the basic limitation of an array that is,
its size cannot be increased or decreased once it is declared. As a result, one ends up reserving
either too much space or too less space for an array and in turn for a stack. This problem can be
overcome if we implement a stack using linked list.

In the case of a linked stack, we shall Push and Pop nodes from one end of a linked list. Each
node in the linked list contains the data and a pointer that gives location of the next node in the

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 2


list. We present a linked-list design for a stack.

Implementation of Stack using Arrays

Operations on stacks

The basic stack operations are

 Push
 Pop
 Peep
 Change
1) Push - Adds an item at the top of the stack.

2) Pop - Pop removes the item at the top of the stack.

3) Peek - returns the value of the Ith element from the top of the stack.

4) Change - changes the value of the Ith element from the top of the stack to the value contained
in ITEM.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 3


Push

Push adds an item at the top of the stack.

Algorithm PUSH(STACK, TOP, MAXSTK, ITEM)


{
int top = 0, ITEM;
int STACK[MAXSTK];
1) // Stack already filled
if(TOP = MAXSTK)
{
printf("\n stack overflow");
return 0;
}
else
{
2) // Inserts ITEM in new Top position
Stack[TOP] = ITEM;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 4


3) // Increases Top by 1
TOP = TOP + 1;
}
Complexity:
Time Complexity: Worst case: O(1)
Space Complexity: Worst case: O(n)

Pop

Pop removes the item at the top of the stack.

Algorithm POP(STACK, TOP, ITEM)


1) // check for underflow on stack
IF TOP = 0
{
printf("\n stack is empty");
return 0;
}
else
2) // Decrement stack top by 1
TOP = TOP - 1

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 5


3) // ASSIGNS TOP element to ITEM
ITEM = STACK[TOP]
return ITEM;
}
4) Stop
Complexity:
Time Complexity: Worst case: O(1)
Space Complexity: Worst case: O(n)

Peek

Peek operation returns the value of the I th element from the top of the stack.

Algorithm PEEK(STACK, TOP, I)

// This function returns the value of the I th element from the top of the stack.

1) // check for underflow on stack

If (TOP < 0)

printf("\n stack UNDERFLOW ON PEEK");

return 0;

else

2) // Return I th element from top of stack

I = STACK[TOP];

return I;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 6


Complexity:
Time Complexity: Worst case: O(n)
Space Complexity: Worst case: O(n)

Change

Algorithm CHANGE(STACK, TOP, ITEM,I)

// This function changes the value of the Ith element from the top of the stack to the value

// contained in ITEM.

1) If TOP <= 0

printf("\n stack UNDERFLOW ON CHANGE");

return 0;

else

2) // Return I th element from top of stack

return(STACK[TOP]) ß ITEM;

Complexity:
Time Complexity: Worst case: O(n)
Space Complexity: Worst case: O(n)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 7


Implementation of Stack using Linked lists
STACK ADT definitions

/ / Stack ADT type definitions

typedef struct node

int data;

struct node *next;

};

typedef struct node NODE

int count;

NODE *top;

};

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 8


Operations on stacks

 Create stack

 Push

 Pop

 Stack top

 Empty stack

 Full stack

 Stack count

 Destroy

1) Create stack

CreateStack allocates memory for the stack structure and allocates a stack head node, initializes
the top pointer to null, and zeros the count field.

Algorithm CreateStack(NODE * head)

// creates an empty stack. Allocates memory for stack head

NODE *stack;

1) stack = ( NODE * ) malloc( sizeof (NODE) );

2) If (stack)

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 9


{

// set count to zero

head àcount = 0;

3) // set top to null

stackàtop = NULL;

return stack;

2) Push

Push operation inserts an element into the stack.

Algorithm PushStack(NODE * stack, )


// This function pushes an item onto the stack.
{
NODE *newnode;
/ * Allocate new node * /
newnode = (NODE *) malloc(sizeof(NODE));
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 10
2) /* Store data in new node */
newnode àdata = num;
3) /* Make current top node the second node */
newnode à link = stack à top;
4) / * Make the new node the top node */
stack à top = newnode;
5) / * Increment the Stack Count * /
(stack àcount ) ++;
return 1;
}
Complexity:
Time Complexity: Worst case: O(n)
Space Complexity: Worst case: O(n)
3) Pop

Pop stack sends the data in the node at the top of the stack back to the calling algorithm. It then
deletes and recycles the node. After the count is adjusted by subtracting one, the function returns
to the caller.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 11


Algorithm PopStack(NODE *stack)
{
NODE *temp;
1) If (stack àcount == 0)
data=null;
else
{
2) /* Set dataOut to data in top node */
temp = stack à top;
data= stack à top àdata;
3) /* Make the second node the top node */
stack à top = stack à top àlink;
free(temp);
4) /* Decrement the Stack count */
(stackàcount)--;
}
} /* end of PopStack */
Complexity:
Time Complexity: Worst case: O(1)
Space Complexity: Worst case: O(n)
4) Stacktop

The stack top function returns the data at the top of the stack without deleting the top node. It
allows the user to see what will be deleted when the stack is popped.

Algorithm Stacktop(NODE *stack)

// This algorithm returns the data from the top of the stack without changing the stack.

1) If (stack àcount > 0 )

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 12


// Set dataout to the top node

return (stack àtop àinfo);

else

return 0;

} // End of stacktop

5) Empty stack

Determines whether the stack is empty or stack has data.

Algorithm emptyStack (NODE *stack)

// This function determines if a stack is empty.

1) // return stack count to zero

return (stack àcount == 0);

} // end of emptystack

6) Full stack

Full stack operation determines if a stack is full. Returns the value true if the stack is full.

Algorithm fullStack (NODE *stack)

// This algorithm determines if a stack is full.

NODE *temp;

1) Check if memory available

If ( ( temp = (STACK_NODE * ) malloc(sizeof (STACK_NODE)));

free ( temp);

return 0;

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 13


}

else

return 1;

} // End of full stack

7) Stack count

Stack count returns the number of items in the stack.

Algorithm stackCount(NODE *stack)

// This function returns the number of elements in the stack.

return(stack àcount);

8) Destroy

Destroy stack operation deletes the nodes in a stack including the stack structure and returns a
NULL pointer.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 14


Algorithm destroyStack (NODE *stack )

// This function deletes all the nodes from the stack including its structure.

NODE *temp;

1) if (stack)

2) // Delete all nodes in the stack

Repeat steps while( stack à top != NULL )

free (stackàtopàdata);

temp = stack à top;

stack à top = stack à top àlink;

free (temp);

} // End of while loop

3) / / Stack now empty. Destroy stack head node

free (stack);

} // End of if

return 0;

} // End of destroyStack

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 15


Applications of Stacks

1) Towers of Hanoi

The Towers of Hanoi is a mathematical game or puzzle. It consists of three pegs, and a number
of disks of different sizes which can slide onto any peg. The puzzle starts with the disks neatly
stacked in order of size on one peg, smallest at the top, thus making a conical shape.

The objective of the game is to move the entire stack to another peg, obeying the following rules:

 Only one disk may be moved at a time.


 Each move consists of taking the upper disk from one of the pegs and sliding it onto
another peg, on top of the other disks that may already be present on that peg.
 No disk may be placed on top of a smaller disk.

The solution to the Towers of Hanoi problem for n>1 disks may be reduced to the following
sub problems:

1) Move the top n-1 disks from peg A to peg B.


2) Move the top disk from peg A to peg C: A C.
3) Move the top n-1 disks from peg B to peg C.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 16


Example:

Towers of Hanoi solution for n=3 disks

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 17


Algorithm Tower (N, BEG, AUX, END)

// This algorithm gives a recursive solution to the Towers of Hanoi problem for N disks.

1) If N=1, then

(a) Write: BEGEND


(b) Return
[End of If structure]

2) // Move N-1 disks from peg BEG to peg AUX

Call TOWER (N-1, BEG, END, AUX)

3) Write: BEGEND

4) // Move N-1 disks from peg AUX to peg END

Call TOWER (N-1, AUX, BEG, END)

5) Return

Complexity:
Time Complexity: Worst case: O(2n)
Space Complexity: Worst case: O(2n)

2) Transforming Infix expressions to Postfix Expressions

The different formats of an arithmetic expression are:


Infix expression
In a infix expression operators are written in between their operands. Infix expression is also
known as Polish notation.
Example:
X+Y
Prefix expression
In a prefix expression operators are written before their operands.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 18


Example:
+XY
Postfix expression
In a prefix expression operators are written after their operands. Postfix expression is also
known as Reverse Polish notation.
Example:
XY+
The algorithm transforms the infix expression Q into its equivalent postfix expression P. The
algorithm uses a stack to temporarily hold operators and left parenthesis. The postfix expression
P will be constructed from left to right using the operands from Q and the operators which are
removed from stack.
The algorithm begins by pushing a left parenthesis onto STACK and adding a right parenthesis
at the end of Q. The algorithm is completed when STACK is empty.
The binary operators in Q will have different levels of precedence. The following three levels of
precedence are assumed for the usual five binary operations:
Highest: Exponentiation ()
Next Highest: Multiplication (*) and division (/)
Lowest: Addition (+) and subtraction (-).
Algorithm POLISH(Q,P)
// Suppose Q is an arithmetic expression written in infix notation. This algorithm finds the
equivalent postfix expression P.
1) Push “(“onto STACK and add “)” to the end of Q.
2) Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the STACK is
empty.
3) If an operand is encountered, add it to P.
4) If a left parenthesis is encountered, push it onto STACK.
5) If an operator  is encountered, then:
(a) Repeatedly pop from STACK and add to P each operator on the top of STACK which has the
same precedence than.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 19


(b) Add  to STACK.
[End of If structure]
6) If a right parenthesis is encountered, then:
(a) Repeatedly pop from STACK and add to P each operator on the top of STACK until a left
parenthesis is encountered.
(b) Remove the left parenthesis. Do not add the left parenthesis to P.
[End of If structure]
[End of step 2 loop]
7) Exit.
Example 1:
Consider the following arithmetic infix expression Q: A+B*C-D/E. Convert the given infix
expression Q into postfix expression P using stacks.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 20


Complexity:
Time Complexity: Worst case: O(n)
Space Complexity: Worst case: O(n)
Example 2:
Consider the following arithmetic expression:

Convert the given infix expression A into postfix expression P using stacks.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 21


Example 3:
Convert the (X - Y / (Z + U) * V) infix expression into postfix expression.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 22


3) Evaluation of a Postfix Expression

Suppose P is an arithmetic expression in postfix notation. The algorithm uses a STACK to hold
operands, evaluates P.

Algorithm EVALUATE POSTFIX(P)


// This algorithm finds the VALUE of an arithmetic expression P written in postfix notation.
1) Add a right parenthesis “)” at the end of P. This acts as a sentinel.
2) Scan P from left to right and repeat steps 3 and 4 for each element of P until the sentinel “)” is
encountered.
3) If an operand is encountered, put it onto STACK.
4) If an operator  is encountered, then:
(a) Remove the two top elements of STACK, where A is the top element and B is the next-to-top
element.
(b) Evaluate BA.
(c) Place the result of (b) back to STACK.
[End of If structure]
5) Set VALUE equal to the top element on STACK.
6) Exit.
Example 1:
Consider the following arithmetic infix expression P: 2, 4, 6, +,*. Evaluate the expression postfix
expression P using stacks. Commas are used to separate the elements of P so that 2, 4, 6 is not
interpreted as the number 246.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 23


Complexity:
Time Complexity: Worst case: O(n)
Space Complexity: Worst case: O(n)
Example 2:
Evaluate the expression postfix expression P

using stacks.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 24


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 25
Converting an Infix Expression to Prefix Expression

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 26


Example:

Consider the following arithmetic infix expression Q:

Evaluate the expression prefix expression P using stacks.

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 27


EVALUATION OF PREFIX EXPRESSION

Example:

Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 28


Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 29
Prepared by Dr.B.GOPI, Asst.Professor, KIST, Kakutur, Nellore, A.P Page 30

You might also like