Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 14

Data Structures

Data Structures
A data structure is a particular way of organizing data in a computer so that it can
be used effectively. The idea is to reduce the space and time complexities of
different tasks. An efficient data structure uses minimum memory space and
execution time to process the structure. A data structure is not only used for
organizing the data. It is also used for processing, retrieving, and storing data.

Type of data structure :


● Linear Data Structure
Data structure in which data elements are arranged sequentially or
linearly, where each element is attached to its previous and next adjacent
elements, is called a linear data structure.
Examples of linear data structures are array, stack, queue, linked list, etc.
1. Static data structure: Static data structure has a fixed memory
size. It is easier to access the elements in a static data structure.
2. Dynamic data structure: In dynamic data structure, the size is
not fixed. It can be randomly updated during the runtime which
may be considered efficient concerning the memory (space)
complexity of the code.
● Non-Linear Data Structure.
Data structures where data elements are not placed sequentially or
linearly are called non-linear data structures. In a non-linear data structure,
we can’t traverse all the elements in a single run only.
Examples of non-linear data structures are trees and graphs.

Stack
A stack is a linear data structure, collection of items of the same type. Stack follows
the Last In First Out (LIFO) fashion wherein the last element entered is the first one
to be popped out. In stacks, the insertion and deletion of elements happen only at
one endpoint of it.
Working of Stacks
● Initially, set a Peek/Top pointer to keep the track of the topmost item in the
stack.
● Initialize the stack to -1. Then, we check whether the stack is empty through
the comparison of Top to -1
● As we add the elements to the stack, the position of the Top element keeps
updating every time.
● As soon as we pop or delete an item from the set of inputs, the top-most
element gets deleted and thus the value of Top gets reduced.
Basic Operations on Stack :
The following are the basic operations served by the Stacks.
● push() to insert an element into the stack
● pop() to remove an element from the stack
● top() Returns the top element of the stack.
● isEmpty() returns true is stack is empty else false
● size() returns the size of stack

Push: Adds an item to the stack. If the stack is full, then it is said to be an Overflow
condition.
Coding:

if(Top==Size-1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter element to be inserted to the stack:");
scanf("%d",&x);
Top=Top+1;
inp_array[Top]=x;
}
Pop: Removes an item from the stack. The items are popped in the reversed order
in which they are pushed. If the stack is empty, then it is said to be an Underflow
condition.
Coding:

if(Top==-1)

{
printf("\nUnderflow!!");
}
else
{
printf("\nPopped element: %d",inp_array[Top]);
Top=Top-1;
}
Top: Returns the top element of the stack.
Coding:

printf("\nTop element: %d",inp_array[Top]);

isEmpty: Returns true if the stack is empty, else false.


Coding:

if(Top==-1)

{
printf("\n Stack is Empty");
}

size() : returns the size of stack

Implementing Stack in C
Stacks can be represented using structures, pointers, arrays or linked lists.
Array Implementation of Stack
Program
#include<stdio.h>
#include<stdlib.h>
#define Size 4
int Top=-1, inp_array[Size];
void Push();
void Pop();
void show();
int main()
{
int choice;
while(1)
{
printf("\nOperations performed by Stack");
printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");
printf("\n\nEnter the choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: Push();
break;
case 2: Pop();
break;
case 3: show();
break;
case 4: exit(0);
default: printf("\nInvalid choice!!");
}
}
}
void Push()
{
int x;

if(Top==Size-1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter element to be inserted to the stack:");
scanf("%d",&x);
Top=Top+1;
inp_array[Top]=x;
}
}

void Pop()
{
if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nPopped element: %d",inp_array[Top]);
Top=Top-1;
}
}

void show()
{

if(Top==-1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nElements present in the stack: \n");
for(int i=Top;i>=0;--i)
printf("%d\n",inp_array[i]);
}
}

Output:

Operations performed by Stack


1.Push the element
2.Pop the element
3.Show
4.End
Enter the choice:1
Enter element to be inserted to the stack:10
Operations performed by Stack
1.Push the element
2.Pop the element
3.Show
4.End
Enter the choice:3
Elements present in the stack:
10
Operations performed by Stack
1.Push the element
2.Pop the element
3.Show
4.End
Enter the choice:2
Popped element: 10
Operations performed by Stack
1.Push the element
2.Pop the element
3.Show
4.End
Enter the choice:3
Underflow!!

Time Complexity
Applications of Stack
● Balancing Parentheses
● String Reverse
● Tower of Hanoi
● Infix to prefix conversion
● N queens problem
1) Balancing Parentheses

Program
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int top = -1;
char stack[100];
// function prototypes
void push(char);
void pop();
void find_top();
void main()
{
int i;
char a[100];
printf("enter expression\n");
scanf("%s", &a);
for (i = 0; a[i] != '\0';i++)
{
if (a[i] == '(')
{
push(a[i]);
}

else if (a[i] == ')')


{
pop();
}
}
find_top();
}
// to push elements in stack
void push(char a)
{
stack[top] = a;
top++;
}
// to pop elements from stack
void pop()
{
if (top == -1)
{
printf("expression is invalid\n");
exit(0);
}
else
{
top--;
}}
// to find top element of stack
void find_top()
{
if (top == -1)
printf("\nexpression is valid\n");
else
printf("\nexpression is invalid\n");
}

2) String Reverse
String : Kongu Engg Reverse : ggnE ugnoK
#include<stdio.h>
#include <stdlib.h>
#include<string.h>
#define SIZE 100
char stack[SIZE];
int Top;
void push(char a);
char pop();
int main()
{
int i;
Top=-1;
char str[SIZE];
printf("Input a string: ");
scanf("%[^\n]s",str); /*read string with spaces*/
/*gets(str);-can be used to read string with spaces*/
for(i=0;i<strlen(str);i++)
push(str[i])
for(i=0;i<strlen(str);i++)
str[i]=pop();
printf("Reversed String is: %s\n",str);
return 0;
}
void push(char a)
{
if(Top>=SIZE-1)
{
printf("\n\tSTACK is FULL");
}
else
{
Top++;
stack[Top]=a;
}
}
char pop()
{
if(Top<=-1)
{
printf("\n\t Stack is Empty");
}
else
{
char temp;
printf("\nThe popped elements is: %c",stack[Top]);
temp=stack[Top];
Top--;
return temp; } }
3) Tower of Hanoi
Tower of Hanoi is a mathematical puzzle where we have three rods and n disks.
The objective of the puzzle is to move the entire stack to another rod, obeying the
following simple rules:
● Only one disk can be moved at a time.
● Each move consists of taking the upper disk from one of the stacks and
placing it on top of another stack i.e. a disk can only be moved if it is the
uppermost disk on a stack.
● No disk may be placed on top of a smaller disk.

Let rod 1 = 'A', rod 2 = 'B', rod 3 = 'C'.


An example with 2 disks :
Step 1 : Shift first disk from 'A' to 'B'.
Step 2 : Shift second disk from 'A' to 'C'.
Step 3 : Shift first disk from 'B' to 'C'.

An example with 3 disks :

Step 1 : Shift first disk from 'A' to 'C'.


Step 2 : Shift second disk from 'A' to 'B'.
Step 3 : Shift first disk from 'C' to 'B'.
----------------------------------------------------
Step 4 : Shift third disk from 'A' to 'C'.
----------------------------------------------------
Step 5 : Shift first disk from 'B' to 'A'.
Step 6 : Shift second disk from 'B' to 'C'.
Step 7 : Shift first disk from 'A' to 'C'.

The pattern here is :


- Shift 'n-1' disks from 'A' to 'B', using C.
---------------------------------------
- Shift last disk from 'A' to 'C'.
---------------------------------------
- Shift 'n-1' disks from 'B' to 'C', using A.
Program
#include <stdio.h>
// C recursive function to solve tower of hanoi puzzle
void towerOfHanoi(int n, char from_rod, char to_rod, char aux_rod)
{
if (n == 1)
{
printf("\n Move disk 1 from rod %c to rod %c", from_rod, to_rod);
return;
}
towerOfHanoi(n-1, from_rod, aux_rod, to_rod);
printf("\n Move disk %d from rod %c to rod %c", n, from_rod, to_rod);
towerOfHanoi(n-1, aux_rod, to_rod, from_rod);
}
int main()
{
int n = 4; // Number of disks
towerOfHanoi(n, \'A\', \'C\', \'B\'); // A, B and C are names of rods
return 0;
}
Output:

Move disk 1 from rod A to rod B


Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 3 from rod A to rod B
Move disk 1 from rod C to rod A
Move disk 2 from rod C to rod B
Move disk 1 from rod A to rod B
Move disk 4 from rod A to rod C
Move disk 1 from rod B to rod C
Move disk 2 from rod B to rod A
Move disk 1 from rod C to rod A
Move disk 3 from rod B to rod C
Move disk 1 from rod A to rod B
Move disk 2 from rod A to rod C
Move disk 1 from rod B to rod C

Time Complexity: O(2n)

Auxiliary Space: O(n)

You might also like