Data Structures Unit-1
Data Structures Unit-1
UNIT-I
Introduction to Data structure
Data structure is a method of organizing a large amount of data more efficiently so that any operation on that data becomes easy
A data structure is a Specific way to store and organize data in a computer's memory so that these data can be used efficiently
later. Data may be arranged in many different ways such as the logical or mathematical model for a particular organization of data
is termed as a data structure.
A data structure is a special way of organizing and storing data in a computer so that it can be used efficiently.
Ex:
List ADT
A list contains elements of same type arranged in sequential order and following operations can be performed on the list.
get() – Return an element from the list at any given position.
insert() – Insert an element at any position of the list.
remove() – Remove the first occurrence of any element from a non-empty list.
removeAt() – Remove the element at a specified location from a non-empty list.
replace() – Replace an element at any position by another element.
size() – Return the number of elements in the list.
isEmpty() – Return true if the list is empty, otherwise return false.
isFull() – Return true if the list is full, otherwise return false.
Note:
1. In a single linked list, the address of the first node is always stored in a reference node known as "front" (Some times it
is also known as "head" or “start”).
2. Always next part (reference part) of the last node must be NULL.
Ex:
Insertion
Deletion
Display
Before we implement actual operations, first we need to set up an empty list. First, perform the following steps before
implementing actual operations.
Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Implement the main method by displaying operations menu and make suitable function calls in the main method to
perform user selected operation.
struct node //Each node in list will contain data and next pointer
{
int data;
struct node *next;
}*start=NULL;
Insertion
In a single linked list, the insertion operation can be performed in three ways. They are as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Deletion
In a single linked list, the deletion operation can be performed in three ways. They are as follows...
Operations
In a circular linked list, we perform the following operations...
Insertion
Deletion
Display
Before we implement actual operations, first we need to setup empty list. First perform the following steps before implementing
actual operations.
Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with two members data and next
Step 4 - Define a Node pointer 'head' and set it to NULL.
Step 5 - Implement the main method by displaying operations menu and make suitable function calls in the main method to
perform user selected operation.
struct node //Each node in list will contain data and next pointer
{
int data;
struct node *next;
}*last=NULL;
}
}
}
}
Deletion
In a circular linked list, the deletion operation can be performed in three ways those are as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
Here, 'link1' field is used to store the address of the previous node in the sequence, 'link2' field is used to store the address of the
next node in the sequence and 'data' field is used to store the actual value of that node.
Note:
1. In double linked list, the first node must be always pointed by head.
2. Always the previous field of the first node must be NULL.
3. Always the next field of the last node must be NULL.
Ex:
Operations:
In a double linked list, we perform the following operations...
1. Insertion
2. Deletion
3. Display
Before we implement actual operations, first we need to set up an empty list. First, perform the following steps before
implementing actual operations.
Step 1 - Include all the header files which are used in the program.
Step 2 - Declare all the user defined functions.
Step 3 - Define a Node structure with three members previous, next and data
Insertion
In a double linked list, the insertion operation can be performed in three ways as follows...
1. Inserting At Beginning of the list
2. Inserting At End of the list
3. Inserting At Specific location in the list
Inserting At Beginning of the list
We can use the following steps to insert a new node at beginning of the double linked list...
Step 1 - Create a newNode with given value and newNode → previous as NULL.
Step 2 - Check whether list is Empty(head == NULL)
Step 3 - If it is Empty then, assign NULL to newNode → next and newNode to head.
Step 4 - If it is not Empty then, assign head to newNode → next and newNode to head.
void insertbeg()
{
struct node *nn;
int a;
nn=(struct node *)malloc(sizeof(struct node));
printf("enter data:");
scanf("%d",&nn->data);
a=nn->data;
nn->next=nn->prev=NULL;
if(start==NULL) //checking if List is empty
{
printf("\n dll is empty, so new node inserted as start node\n");
start=nn;
}
else //list contains elements
{
nn->next=start;
start->prev=nn;
start=nn;
}
printf("\n %d succesfully inserted\n",a);
}
Deletion
In a double linked list, the deletion operation can be performed in three ways as follows...
1. Deleting from Beginning of the list
2. Deleting from End of the list
3. Deleting a Specific Node
}
}
}
Stack ADT
Stack is a linear data structure in which the operations are performed based on LIFO principle.
"A Collection of similar data items in which both insertion and deletion operations are performed based on LIFO principle".
Stack is a linear data structure in which the insertion and deletion operations are performed at only one end.
In a stack, adding and removing of elements are performed at a single position which is known as "top". That means, a new
element is added at top of the stack and an element is removed from the top of the stack. In stack, the insertion and deletion
operations are performed based on LIFO (Last In First Out) or FILO (First In Last Out) principle.
In a stack, the insertion operation is performed using a function called "push" and deletion operation is performed using a
function called "pop".
In the figure, PUSH and POP operations are performed at a top position in the stack. That means, both the insertion and deletion
operations are performed at one end (i.e., at Top)
Ex:
If we want to create a stack by inserting elements like 10, 45, 12, 16, 35 and 50. Then 10 becomes the bottom-most element and
50 is the topmost element. The last inserted element 50 is at Top of the stack as shown in the image below...
Operations on a Stack
The following operations are performed on the stack...
1. Push (To insert an element on to the stack)
2. Pop (To delete an element from the stack)
3. Display (To display elements of the stack)
In linked list implementation of a stack, every new element is inserted as 'top' element. That means every newly inserted element
is pointed by 'top'. Whenever we want to remove an element from the stack, simply remove the node which is pointed by ' top' by
moving 'top' to its previous node in the list. The next field of the first element must be always NULL.
In the above example, the last inserted node is 99 and the first inserted node is 25. The order of elements inserted is 25, 32,50 and
99.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
}*top=NULL,*top1,*temp;
void push()
{
int element;
printf("enter the element\n");
scanf("%d",&element);
We can use the following steps to delete a node from the stack...
Expressions
In any programming language, if we want to perform any calculation or to frame a condition etc., we use a set of symbols to
perform the task. These set of symbols makes an expression.
In above definition, operator is a symbol which performs a particular task like arithmetic operation or logical operation or
conditional operation etc.,
Operands are the values on which the operators can perform the task. Here operand can be a direct value or variable or address
of memory location.
Expression Types
Based on the operator position, expressions are divided into 3 types. They are as follows...
1. Infix Expression
2. Postfix Expression
3. Prefix Expression
Infix Expression
In infix expression, operator is used in between the operands.
The general structure of an Infix expression is as follows...
Ex:
Postfix Expression
In postfix expression, operator is used after operands. We can say that "Operator follows the Operands".
The general structure of Postfix expression is as follows...
In prefix expression, operator is used before operands. We can say that "Operands follows the Operator".
The general structure of Prefix expression is as follows...
Operator Operand1 Operand2
Ex:
Every expression can be represented using all the above three different types of expressions. And we can convert an expression
from one form to another form like Infix to Postfix, Infix to Prefix, Prefix to Postfix and vice versa.
To convert any Infix expression into Postfix or Prefix expression we can use the following procedure...
1. Find all the operators in the given Infix Expression.
2. Find the order of operators evaluated according to their Operator precedence.
3. Convert each operator into required type of expression (Postfix or Prefix) in the same order.
Ex:
Consider the following Infix Expression to be converted into Postfix Expression...
D=A+B*C
Step 1 - The Operators in the given Infix Expression : = , + , *
Step 2 - The Order of Operators according to their preference : * , + , =
Step 3 - Now, convert the first operator * ----- D = A + B C *
Step 4 - Convert the next operator + ----- D = A BC* +
Step 5 - Convert the next operator = ----- D ABC*+ =
To convert Infix Expression into Postfix Expression using a stack data structure, We can use the following steps...
1. Read all the symbols one by one from left to right in the given Infix Expression.
2. If the reading symbol is operand, then directly print it to the result (Output).
3. If the reading symbol is left parenthesis '(', then Push it on to the Stack.
4. If the reading symbol is right parenthesis ')', then Pop all the contents of stack until respective left parenthesis is poped and
print each poped symbol to the result.
5. If the reading symbol is operator (+ , - , * , / etc.,), then Push it on to the Stack. However, first pop the operators which are
already on the stack that have higher or equal precedence than current operator and print them to the result.
Ex:
Consider the following Infix Expression...
(A+B)*(C-D)
The given infix expression can be converted into postfix expression using Stack data Structure as follows...
Ex:
1. Read all the symbols one by one from left to right in the given Postfix Expression
2. If the reading symbol is operand, then push it on to the Stack.
3. If the reading symbol is operator (+ , - , * , / etc.,), then perform TWO pop operations and store the two popped oparands in
two different variables (operand1 and operand2). Then perform reading symbol operation using operand1 and operand2 and push
result back on to the Stack.
4. Finally! perform a pop operation and display the popped value as final result.
Ex:
void main()
{
printf("\n Enter the infix expression:");
scanf("%s",infix);
postfix();
}
void postfix()
{
int i,j=0;
for(i=0; infix[i]!=0; i++)
{
switch(infix[i])
{
case '+': while(stack[top] >= 1)
post[j++]=pop();
push(1);
break;
case '-': while(stack[top] >= 1)
post[j++]=pop();
push(2);
break;
case '*': while(stack[top] >= 3)
post[j++]=pop();
push(3);
break;
case '/': while(stack[top] >= 3)
post[j++]=pop();
push(4);
break;
case '^': while(stack[top] >= 4)
post[j++]=pop();
push(5);
break;
case '(': push(0);
break;
case ')': while(stack[top] != 0)
post[j++]=pop();
top--;
break;
default: post[j++]=infix[i];
}
}
while(top>0)
{
post[j++]=pop();
}
printf("\n Postfix Expression is => %s\n", post);
}
Expression = (A+B^C)*D+E^5
Step 1. Reverse the infix expression.
5^E+D*)C^B+A(
Step 2. Make Every '(' as ')' and every ')' as '('
5^E+D*(C^B+A)
Step 3. Convert expression to postfix form.
A+(B*C-(D/E-F)*G)*H
char infix[50],post[50],*pre,*rev;
int top=0, stack[20];
void postfix();
void push(int);
char pop();
int main()
{
printf("\n Enter the infix expression:");
scanf("%s",infix);
rev=strrev(infix);
postfix();
return 0;
}
void postfix()
{
int i,j=0;
for(i=0; rev[i]!=0; i++)
{
switch(rev[i])
{
case '+': while(stack[top] >= 1)
post[j++]=pop();
push(1);
break;
case '-': while(stack[top] >= 1)
post[j++]=pop();
push(2);
break;
case '*': while(stack[top] >= 3)
post[j++]=pop();
push(3);
break;
case '/': while(stack[top] >= 3)
post[j++]=pop();
push(4);
break;
case '^': while(stack[top] >= 4)
post[j++]=pop();
push(5);
break;
case '(': push(0);
break;
case ')': while(stack[top] != 0)
post[j++]=pop();
top--;
break;
default: post[j++]=rev[i];
}
}
while(top>0)
{
post[j++]=pop();
}
pre=strrev(post);
printf("\n Prefix Expression is => %s", pre);
}
Queue ADT
Queue is a linear data structure in which the insertion and deletion operations are performed at two different ends. In a queue data
structure, adding and removing elements are performed at two different positions. The insertion is performed at one end and
In a queue data structure, the insertion operation is performed using a function called "enQueue()" and deletion operation is
performed using a function called "deQueue()".
Queue data structure is a linear data structure in which the operations are performed based on FIFO principle.
"Queue data structure is a collection of similar data items in which insertion and deletion operations are performed based on FIFO
principle".
Ex:
Queue after inserting 25, 30, 51, 60 and 85.
Operations on a Queue
The following operations are performed on a queue data structure...
Queue data structure can be implemented in two ways. They are as follows...
1. Using Array
2. Using Linked List
When a queue is implemented using an array, that queue can organize an only limited number of elements. When a queue is
implemented using a linked list, that queue can organize an unlimited number of elements.
Step 1 - Include all the header files which are used in the program and define a constant 'SIZE' with specific value.
Step 2 - Declare all the user defined functions which are used in queue implementation.
Step 3 - Create a one dimensional array with above defined SIZE (int queue[SIZE])
Step 4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'. (int front = -1, rear = -1)
Step 5 - Then implement main method by displaying menu of operations list and make suitable function calls to perform
operation selected by the user on queue.
#define max 6
int queue[max],front=-1,rear=-1;
void add();
void del();
void display();
void main()
{
int choice;
while(1)
{
printf("enter the choice\n");
printf("\n1.Add\n2.Delete\n3.Display\n4.Exit\n");
printf("\nenter the choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: add();break;
case 2: del();break;
case 3: display();break;
case 4:exit(0);
default: printf("you have entered wrong choice\n");
}
}
}
In linked list implementation of a queue, the last inserted node is always pointed by 'rear' and the first node is always pointed by
'front'.
Ex:
In above example, the last inserted node is 50 and it is pointed by 'rear' and the first inserted node is 10 and it is pointed by
'front'. The order of elements inserted is 10, 15, 22 and 50.
Operations
To implement queue using linked list, we need to set the following things before implementing actual operations.
Step 1 - Include all the header files which are used in the program. And declare all the user defined functions.
Step 2 - Define a 'Node' structure with two members data and next.
void insert(int);
void delete();
void display();
void main()
{
int choice, value;
clrscr();
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be insert: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
Step 1 - Create a newNode with given value and set 'newNode → next' to NULL.
Step 2 - Check whether queue is Empty (rear == NULL)
Step 3 - If it is Empty then, set front = newNode and rear = newNode.
Step 4 - If it is Not Empty then, set rear → next = newNode and rear = newNode.
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Success!!!\n");
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}