0% found this document useful (0 votes)
7 views26 pages

Stack

A stack is a linear data structure that operates in a Last In First Out (LIFO) manner, allowing elements to be added or removed only from the top. It can be implemented statically using an array or dynamically using a linked list, with various operations such as push, pop, and peek performed in O(1) time. Stacks have numerous applications, including function call management, expression evaluation, and backtracking algorithms.

Uploaded by

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

Stack

A stack is a linear data structure that operates in a Last In First Out (LIFO) manner, allowing elements to be added or removed only from the top. It can be implemented statically using an array or dynamically using a linked list, with various operations such as push, pop, and peek performed in O(1) time. Stacks have numerous applications, including function call management, expression evaluation, and backtracking algorithms.

Uploaded by

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

Stack

Introduction

 Array and linked list are both linear data structures that allow the
user to store, access and modify elements at any position.
However, some applications require the data elements to be
accessed only in a specific manner. Many times we see chairs
placed in a neat pile or stack. If you want a chair to sit, you would
remove the topmost chair. It is impossible to remove any other
chair. Moreover, every new chair has to be placed on the top of
the pile. You cannot insert it in the middle of the pile. Thus, the
only two operations are:1. Remove the topmost chair.2. Add a
chair to the top of the pile.This is how a stack works. A Stack is a
linear data structure in which elements can be accessed in the
Last-in-First-out manner.
Definition

 A Stack is an ordered collection of items which are arranged in


the Last In First Out (LIFO) manner. It has one open end called
'top' and elements can be added (PUSH) and removed (POP) from
the same end. The following diagram illustrates a Stack after
PUSH and POP operations have been performed.

 Implementation
 A stack can be implemented in two ways:.
 1. Static implementation using array
 2. Dynamic implementation using linked list
Primitive Operations on a Stack

 i. Create: This operation creates a new stack, which is initially


empty.
 ii. Push: The push operation adds a new element at the top of the
stack. Top points to the new element.
 Iii. Pop: Removes the topmost element from the stack. The next
element now becomes the topmost element.
 iv. IsEmpty: This operation returns TRUE if the stack is empty and
false otherwise. Popping from an empty stack causes an
Underflow.
 V. IsFull: This operation returns TRUE if the stack is full and false
otherwise. Pushing into a full stack causes an Overflow.
Static Implementation of Stack

 Since the stack contains a set of zero or more elements, we can


implement it using an array. The stack elements will be stored as
array elements and stack operations will be performed on the
array. However, since the stack operations are performed from
only one end called 'Top', we have to remember the position of
the topmost element in the array.
 A stock implemented using an array will require:
 An array to store stack elements.
 An integer called top which stores the index of the topmost element.
 We can use a structure for the above purpose.
 #define MAXSIZE 100
 typedef struct stack
{
int data [MAXSIZE],
int top;
}STACK;
Stack Operations

 Create: To create a stack, we must create a variable of the above


structure and initialize top so that it indicates an empty stack.
 Example
 STACK s;
 Initialize: We will initialize top to -1 since the first array index is 0.
 s.top = -1;
 IsEmpty: If top contains -1, it indicates an empty stack. Hence,
the condition will be:
 if (s.top ==-1)
 IsFull: If the value of top reaches the maximum array index, i.e.,
MAXSIZE-1, no more elements can be pushed into the stack. Hence,
the Stack full condition will be:
 if (s.top==MAXSIZE-1)
 5. Push: To push an element in the stack, top must be incremented
first. The element to be pushed is stored in the array at the top
position.
 Hence, the statements will be:
 s.top++;
 s.data[s.top]=element;
 The Push operation can be performed only if the stack is not full
otherwise it causes an Overflow.
 6. Pop: This operation removes the topmost element from the
stack. After this, top must he decremented. Hence, the
statements will be:
 Elements=s.data[s.top];
 s.top--;
 The Pop operation can be performed only if the stack is not
empty otherwise it causes an Underflow.
 7. Peek: This function allows the topmost element in the stack to
be accessed without popping the element. Hence top is not
decremented here.
 element s.data[s.top];
 Time Complexity of Operations
 All stack operations are performed in O(1) time.
 Advantages of static implementation
 1. Since we use an array to implement stack, operations can be
easily performed.
 2.Time complexity of operations is O(1).
 Limitations of static implementation
 1. Since array is a static data structure, the size has to be
declared at the beginning.
 2. The size of the stack remains fixed. Even if the stack is empty,
memory remains allocated
 3. The size of the stack is limited by the size of the array.
 Dynamic Implementation of Stack
 To overcome the limitations of the static implementation, the
stack can be implemented dynamically. In this method, we use
dynamic memory allocation. Memory is allocated only when an
element is Pushed and deallocated when an element is Popped.
Hence, the size of the stack increases or shrinks dynamically.
 In dynamic memory allocation, the memory is allocated
randomly. Hence, the stack elements will not occupy consecutive
memory locations. So, the elements must be linked to one
another. Thus, the stack can be implemented as a linked list.
 In the linked representation, the stack is maintained as a linked
set of nodes. An external pointer called "top" stores the address
of the first node. For Push operation, a node is created and added
to the beginning of the list. To pop, the first node is deleted and
the next node becomes the topmost node. For example, if 10. 20
and 30 are pushed, the stack will look like
 Node structure
 typedef struct node
 {
 int info;
 struct node *next;
 }NODE;
 Operations
 1. Create: To create a dynamic stack, we declare top as a pointer
to the node.
 NODE * top;
 Initialize: Initially, the stack is empty, hence top is initialized to
NULL.
 top = NULL;
 3. Push: To Push an element in the stack, we must create a new
node. The new node is inserted at the beginning of the list and
top will point to this node. The steps are:
 newnode =(NODE*)malloc(sizeof(NODE));
 newnode->info=num;
 newnode->next=top;
 Top=newnode;
 Pop: The element from the first node is popped, the node is
deleted and its next node becomes topmost node of the stack.
 Temp=top;
 Num=top->info;
 Top=top->next;
 free temp);
 5. Peek: This is similar to pop operation. However, we only access
the topmost element without popping it.
 Num=top->info;
 6. IsEmpty: If top contains NULL, it indicates that there are no
nodes and the stack is empty.
 if (top==NULL)
 IsFull: Since we are using dynamic memory allocation, the stack
can grow to any size, Thus, this condition is not applicable in the
dynamic implementation.
 Time Complexity of Operations
 All stack operations are performed in O(1) time.
Advantages of Dynamic
Implementation
 1. The stack can grow to any size.
 2. We need not have prior knowledge of the number of elements.
 3. Efficient utilization of memory. Memory is allocated only when
an element is pushed and freed when an element is popped.
 Limitations of Dynamic Implementation
 1. The implementation is complex compared to static
implementation.
 2. Additional memory is required for the pointers.
Applications of Stack
 A Stack is widely used in several applications. Some of the
applications are:
 1.Handling function calls, Recursion.
 2. Interrupt handling in processors.
 3. Compilers and operating systems.
 4.Expression conversion and evaluation (Infix, Postfix and Prefix
expressions).
 5. Non recursive traversal of tree and graph.
 6. Checking whether parentheses are matching in an expression.
 7. String reversal and palindrome checking.
 8. Backtracking algorithms.
 9. Games.
Prefix, Infix and Postfix
Expressions
 An expression consists of operators and operands. The operands
are identifiers or constants. Operators are symbols representing
various operations. An expression can be written in three formats
depending upon the location of operators with respect to the1.
operands.
 1. Infix: In the infix notation, the operand is placed between the
operands. An infix expression may contain brackets.
 Example: A+B, (A+B)*C, (A+B)*(C-D)
 2. Prefix: In the prefix form, the operator is written before the
operands. This format is non-parenthesized, i.e., does not contain
any brackets. It is also called Polish notation.
 Example: +AB, *+ABC, *+AB-CD
 3. Postfix: In this format, the operator follows the operands. This
format is non-parenthesized, i.e., does not contain any brackets.
It is also called Reverse Polish notation.
 Example: AB+, AB+C*, AB+CD-*
 Advantage of Prefix and Postfix notations
 Prefix and Postfix notations do not contain brackets, hence they
are evaluated faster. The compiler converts an infix expression to
the postfix format before evaluating it.
Converting Infix to Prefix and
Postfix form
 To convert an infix expression to Prefix and Postfix, the conversion is done by
taking one operator at a time and converting only that expression. The
operators are converted according to their priority. The priority of operators is
considered as follows:
 1. Brackets
 2 Exponentiation ($ or^)
 3. Arithmetic (*/%)
 4. Arithmetic (+-)
 For example, in the infix expression A+B*C, * will be converted first according
to priority and + will be converted last. Hence, the prefix of A+B*C is +A*BC
and postfix is ABC*+. The following table shows the conversion of infix
expressions to prefix and postfix. Only one operator is converted at a time.
 The operator being converted at every step is shown underlined.
 The above conversions can also be done by the following steps
 1. Completely parenthesize the infix expression to specify the
order of operations
 2. Move each operator outside its corresponding left parenthesis
(for Prefix) of right parenthesis (for Postfix).
 3 Remove all parentheses
 Example
 We will now see an algorithm to convert infix to postfix
expression,To convert an infix expression to postfix, we will need
 1. An infix string.
 2. A stack (opstk) which will store the operators.
 3. A string to store the postfix expression.
 4. Priority of operators
 The priorities assigned will be as follows.
 The infix string can have operands, operators, opening and
closing brackets. Thus, we have 4 cases:
 1. If it is an operand, we add it to postfix string.
 2. If it is an opening bracket, we push it into the stack.
 3. If it is a closing bracket, we pop till we get an opening bracket
and add to the postfix string.
 4. If it is an operator, we have to check the priority of the
operator in the stack. If the operator in the stack has a higher
priority, then it should be popped and added to postfix string and
the current operator must be pushed in the stack.

You might also like