Data Structures: CS 201 Radhamadhab Dalai Asst. Professor CSE BIT Mesra, Ranchi

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 12

Data Structures

CS 201
Radhamadhab Dalai
Asst. Professor
CSE
BIT Mesra, Ranchi

19-08-2020 1
Stack : Introduction
• Stack is an ADT which works in principle of
Last in First Out.
• Last element to be inserted into stack is the
first one to be deleted.
• Insertion and deletion happens at one end
known as top.
• It is visualised as pile of items arranged in one
above other.

19-08-2020 2
Introduction contd….

D TOP Push

Pop
A

19-08-2020 3
Stack operations
• It is a linear data structure

• Push ,Pop, Display


Empty

Push(22) Push(4) Pop() 4

top

top 4
top
top
22 22
22

19-08-2020 4
Implementations
• Using Arrays using C.
• Declaration

int stack[100],n, top, i =-1;


// n is a variable to track maximum elements
// 100 maximum elements
// i is a variable to increment and decrement
• Overflow condition
if(top>=n-1)
{
printf("stack is over flow");
}

19-08-2020 5
Implementations
• Underflow conditions:
if(top<=-1)
{
printf(“stack is under flow");
}

19-08-2020 6
Push Operation
• Check overflow condition.
• printf(" Enter a value to be pushed:");
scanf("%d",&x);
top++;
stack[top]=x;

19-08-2020 7
Pop Operations
• Check Underflow condition first
• printf("The popped element is %d",
stack[top]);
or return stack[top];
top--; }

19-08-2020 8
Display
• if(top>=0)
{
printf("The elements in stack\n");
for(i=top; i>=0; i--)
printf("%d", stack[i]);
}
else {
?????????
}

19-08-2020 9
Examples
• Stack is used in parenthesis matching, post fix
evaluation, recursion, symbol table etc.
• Real life example:
Favourite book in rack

19-08-2020 10
Linked Lists
• Singly Linked Lists:
• struct node {
int data;
struct node * next;
};

A Next B Next

NULL

19-08-2020 11
Operations
• It is linear data structure.
• Operations:
1. Insertion 2. deletion 3. traverse
• 3. Traverse operation
Find out the length of list (number of nodes in the list)

int findListLength(Struct node *head)


{
struct node *current = head;
while(current ! = NULL)
?
current = current -> next;
?
}

19-08-2020 12

You might also like