DATA STRUCTURE LAB. PROGRAMS


// Program to Implement Several Operations on Linked List
  
#include<stdio.h>
#include<stlib.h>
#include<conio.h>
struct node;
typedef struct node *ptr;
typedef ptr list;
typedef ptr position;
typedef int data;
struct node
{
data element;
struct node *next;
}
//function prototypes
void makeempty(void);    //to make empty list
int isempty(void);           //to check list is empty or not
void create(void);            //to create initial set of elements
position findprevious(data); //to find position of previous element
void delet(data);              //to delete given element
void display(void);                    //to display all the elements
void insert(data, int);      //to insert a new element
position getprevposition(int); //to find position of previous element
data getelement(int);      //to find the element at given position
int getposition(data); /   /to find position of given element
//global variable declarations
position first;
position last;
position L;
int length;
//to make empty list
void makeempty(void)
{
position tmp;
tmp = malloc(sizeof(list));
tmp->next = NULL;
L = tmp;
first = last = NULL;
}
//to check list is empty or not
int isempty(void)
{
if (L->next = NULL)
return 1;
else
return 0;
}
//to create initial set of elements
void create(void)
{
data e;
int n, i;
position tmp;
makeempty();
printf(“Enter number of element : \ “);
scanf(“%d”, &n);
for (i=0; i<n; i++)
{
printf(“Enter an element : “);
scanf(“%d”, &e);
tmp = malloc(sizeof(list));
tmp->element = e;
tmp->next = NULL;
if (L->next == NULL)
{
L->next = tmp;
first = last = tmp;
}
else
{
last->next = tmp;
last = tmp;
}
}
}
//to display all the elements
void display()
{
position t;
for(t=first; t!=NULL; t=t->next)
printf(“%d --> “, t->element);
getch();
}
//to find position of previous element
position getprevposition(int index)
{
position tmp;
int count = 1;
if (index>length)
{
printf(“Invalid Position”);
return NULL;
}
else
{
for (tmp=first; count<index-1; tmp=tmp->next)
count++;
return tmp;
}
}
//to insert a new element
void insert(data x, int p)
{
position pos, tmp;
tmp = malloc(sizeof(list));
tmp->element=x;
if (p==1) //first position
{
tmp->next = first;
L->next = tmp;
first = tmp;
length++;
}
else if (p == length)                  //last position
{
last->next = tmp;
last = tmp;
tmp->next = NULL;
}
else //arbitrary position
{
pos = getpreviousposition(p);
if (pos == NULL)
{
printf(“Invalid position”);
getch();
}
else
{
tmp->next = pos->next;
pos->next = tmp;
length++;
}
}
}
//to find position of previous element
position findprevious(data x)
{
position p;
p = L;
while (p->next->element!=x && p->next!=NULL)
p = p->next;
return p;
}
//to delete given element
void delet(data x)
{
position p, tmp;
if (isempty())
{
printf(“List is empty”);
getch();
}
else
{
p = findprevious(x);
if (p->next = NULL)
{
printf(“Element not found”);
getch();
}
else
{
if (p->next == last)
{
free (p->next);
p->next = NULL;
last = p;
length--;
return;
}
if (p == L)
{
first = first->next;
}t
mp = p->next;
p->next = tmp->next;
free(tmp);
length--;
}
}
}
int menu()
{
int ch;
printf(“1. Create\n2. Display\n3.Insert\n4.Get Element\n5.Get Position\n6. Delete\n7.
Exit\n\n Enter your choice : “);
scanf(“%d”, &choice);
return choice;
}
//to find the element at given position
data getelement(int pos)
{
position p;
int i;
p = L;
if (pos > length)
return NULL;
else
{
for(i=0; i<pos; i++)
p = p->next;
return p->element;
}
}
//to find position of given element
int getposition(data e)
{
position p;
int i=0;
for (p=first; p!=NULL; p=p->next)
{
if (p->element == e)
return i+1;
else
i++;
}
return NULL;
}
void main()
{
int ch;
data n, p;
while(1)
{
clrscr();
ch = menu();
switch (ch)
{
case 1: create();
break;
case 2: display();
break;
case 3: printf(“Enter an element : “);
scanf(“%d”, &n);
printf(“Enter Position : “);
scanf(“%d”, &p);
insert (n, p);
break;
case 4: printf(“Enter an element : “);
scanf(“%d”, &n);
delet (n);
break;
case 5: printf(“Enter position : “);
scanf(“%d”, &p);
if (p<1 || p>length)
printf(“Invalid position”);
else
printf(“Element at position %d is %d”, p,
getelement(p));
getch();
break;
case 6: printf(“Enter an element : “);
scanf(“%d”, &n);
if (getposition(n) == NULL)
printf(“Element doesn’t Exist”);
else
printf(“%d exists at position %d”, n, getposition(n));
getch();
break;
default:
printf(“Invalid Choice”);
getch();
}
}
}


---------------- Output ----------------

1. Create
2. Display
3. Insert
4. Delete
5. Get element
6. Get position
7. Exit
Enter your Choice: 1
Enter number of element: 3
Enter an element: 10
Enter an element: 20
Enter an element: 30
Enter your Choice: 3
Enter element: 25
Enter Position: 3
Enter your Choice: 2
10 --> 20 --> 25 --> 30
Enter your Choice: 6
Enter an element:20
20 exists at position 2
Enter your Choice: 4
Enter an element 30
Enter your Choice: 2
10 --> 20 --> 25
Enter your Choice: 7


_____________________http://sundcs.blogspot.com/_________________


//Program to implement Stack using Arrays

#include<iostream.h>
#define MAX 10
int stack[10],i,top=-1,x,ch;
void push()
{
if(top==MAX-1)
cout<< "\n Stack Overflow \n";
else
{
cout<< "\n enter any element ";
 cin>>x;
stack[++top]=x;
}
}
void pop()
{
if(top==-1)
cout<< "/n Stack Underflow";
else
{
x=stack[top--];
cout<<"\n Poped element is \n"<<x;
}
}
void display()
{
 if(top==-1)
 cout<<"\n Stack Underflow";
else
{
cout<<"\t Stack elements are ";
for(i=0;i<=top;i++)
cout<<"\t" <<stack[i];
}
}
void main()
{
do
{
cout<< "\n 1.Push";
cout<< "\n 2.pop";
cout<< "\n 3.display";
cout<< "\n 4.exit";
cout<< "\n enter your choice[1..4] \n";
cin>>ch;
switch(ch)
{
case 1:push();
break;
case 2:pop();
break;
case 3:display();
break;
}
}
while(ch!=4);
}
----------------OUTPUT----------------
 1.Push
 2.pop
 3.display
 4.exit
 enter your choice[1..4]
1
enter any element 44

1.Push
 2.pop
 3.display
 4.exit
 enter your choice[1..4]
1
enter any element 74

1.Push
 2.pop
 3.display
 4.exit
 enter your choice[1..4]
3
           Stack elements are     44      74
 1.Push
 2.pop
 3.display
 4.exit
 enter your choice[1..4]
2

 Poped element is
74
 1.Push
 2.pop
 3.display
 4.exit
 enter your choice[1..4]                                                        
3                                                                              
         Stack elements are     44                                             
 1.Push                                                                        
 2.pop                                                                          
 3.display                                                                     
 4.exit                                                                        
 enter your choice[1..4]                                                       
4                                                                              



_____________________http://sundcs.blogspot.com/_________________



 //Program to implement Stack using Linked List

#include<stdio.h>
#include<conio.h>
# include "malloc.h"
struct node
{
int data;
struct node *link;
} ;
struct node *top;
void main()
{
void push(int);
void display();
int wish, num,will,a;
wish = 1;
top = NULL;
clrscr();
printf("Program for Stack as Linked List demo..");
while(wish == 1)
{printf(" Main Menu 1.Enter data in stack 2.Delete from stack ");
scanf("%d",&will);
switch(will)
{
case 1: printf("Enter the data");
scanf("%d",&num);
push(num);
display();
break;
case 2: a=pop();
printf("Value returned from top of the stack is %d",a);
break;
default:
printf("Invalid choice");
}
printf("Do you want to continue, press 1");
scanf("%d",&wish);
}
}
void push(int y)
{
struct node *x;
x=malloc(sizeof(struct node));
printf("Address of newly created node x is %d",x);
x->data = y;
x->link = top;
top = x;
}
void display()
{
int i =0;
struct node * temp;
temp = top;
while(temp!=NULL)
{
printf("Item No. %d : Data %d Link %d ",i++,temp->data, temp->link);
temp=temp->link;
}
}
/*this function removes top node from the stack and
returns its value*/
int pop()
{
int a;
if(top==NULL)
{
printf("STACK EMPTY...");
return 0;
}
else
{
a=top->data;
printf("The value returned is %d ",a);
free(top);
top=top->link; return (a);
}
}    



_____________________http://sundcs.blogspot.com/_________________



//Program to implement Circular Queue

# include<stdio.h>
# include<string.h>
# include<ctype.h>
# include<stdlib.h>
# define size 6
int l, u; /* l means lower bound u means upper bound */
int rear, front;
int ch;
int q[size];
int rear = -1;
int front = -1;
void insert_queue();
void delete_queue();
void display_queue();
/* function to create queue */
void insert_queue()
{
if ((front == 0) && (rear == size-1))
{
printf("\n overflow");
rear = 1;
return;
}
else
if (front < 0) /* insert first element */
{
front = 0;
rear = 0;
printf("\ninput the element :");
scanf("%d", &ch);
q[rear] = ch ;
}
else
if (rear == size-1)
{
rear = 0;
printf("\n input the element :");
scanf("%d", &ch);
q[rear] = ch ;
}
else
{
rear ++;
printf("\n input the element :");
scanf("%d", &ch);
q[rear] = ch ;
}
}
/* function to perform delete operation */
void delete_queue()
{
if (front < 0)
{
printf("\nunderflow");
return ;
}
ch = q[front];
q[front] = null;
printf("\n element deleted :", ch);
if(front == rear)
{
front = -1;
rear = -1;
}
else
if ( front == size-1)
{
front = 0;
}
else
{
front++ ;
}
}
/* output function */
void display_queue()
{
int i;
if (front < 0)
return;
if ( rear >= front)
{
for(i = front; i <= rear; i++)
{
printf("\n i = %d", i);
printf(" %d ", q[i]);
}
}
else
{
for(i = front; i < size; i++)
{
printf("\n i = %d", i);
printf(" %d", q[i]);
}
for(i = 0; i <= rear; i++)
{
printf("\n i = %d", i);
printf(" %d ", q[i]);
}
}
}
/* function main */
void main()
{
int k = 0;
char choice;
do
{
printf("\ninsert->i delete->d quit->q:");
printf("\ninput the choice : ");
do
{
choice = getchar();
choice = tolower(choice);
}while(strchr("idq",choice)==null);
printf("your choice is: %c",choice);
switch(choice)
{
case 'i' :
insert_queue();
printf("\nqueue after inserting ");
display_queue();
break;
case 'd' :
delete_queue();
printf("\nqueue content after deleteion is as follows:\n");
display_queue();
break;
case 'q':
k = 1;
}
} while(!k);




_____________________http://sundcs.blogspot.com/_________________


//  Program to Implement Queue using Linked List

#include<iostream.h>
#include<conio.h>
class Queue{
          private:
                   int *val;
                   int front,rear;
                   int size;
          public:
                   Queue(int s=5){
                             size=s;
                             val=new int[size];
                             front=rear=size-1;
                   }
                   void enQueue(int x){
                             if((rear+1)%size==front)
                                      cout<<"\n Queue Overflow";
                             else{
                                      rear=(rear+1)%size;
                                      val[rear]=x;
                             }
                   }
                   int deQueue(){
                             if(front==rear){
                                      cout<<"\n Queue Underflow";
                                      return -1;
                             }
                             else{
                                      front=(front+1)%size;
                                      int x=val[front];

                                      return x;
                             }
                   }

} ;
void main(){
          Queue q;
          clrscr();
          cout<<"\n"<<q.deQueue();
          q.enQueue(1);
          q.enQueue(2);
          q.enQueue(3);
          q.enQueue(4);
          q.enQueue(5);
          cout<<"\n"<<q.deQueue();
          cout<<"\n"<<q.deQueue();
          cout<<"\n"<<q.deQueue();
          cout<<"\n"<<q.deQueue();
          cout<<"\n"<<q.deQueue();
          cout<<"\n"<<q.deQueue();
          q.enQueue(1);
          getch();
}

---------------- OUTPUT ----------------


 Queue Underflow
-1
 Queue Overflow
1
2
3
4
 Queue Underflow
-1
 Queue Underflow
-1




_____________________http://sundcs.blogspot.com/_________________



//Program to Evaluate Postfix Expression

#include<stdio.h>
#include<conio.h>
float stack[10];
int top=-1;
void push(char);
float pop();
float eval(char[],float[]);
void main()
{
int i=0;
char suffix[20];
float value[20],result;
clrscr();
printf("Enter a valid postfix expression:\n");
gets(suffix);
while(suffix[i]!='\0')
{
if(isalpha(suffix[i]))
{
fflush(stdin);
printf("Enter the value of %c:\n",suffix[i]);
scanf("%f",&value[i]);
}
i++;
}
result=eval(suffix,value);
printf("The result of %s is = %f",suffix,result);
getch();
}
float eval(char suffix[],float data[])
{
int i=0;
float op1,op2,res;
char ch;
while((suffix[i])!='\0')
{
ch=suffix[i];
if(isalpha(suffix[i]))
{
push(data[i]);
}
else
{
op2=pop();
op1=pop();
switch(ch)
{
case '+' : push(op1+op2);
break;
case '-' : push(op1-op2);
break;
case '*' : push(op1*op2);
break;
case '/' : push(op1/op2);
break;
case '^' : push(pow(op1,op2));
break;
}
}
i++;
}
res=pop();
return(res);
}
void push(char num)
{
top=top+1;
stack[top]=num;
}
float pop()
{
float num;
num=stack[top];
top=top-1;
return(num);
}




----------------- OUTPUT ---------------------


Enter a valid postfix expression:
ab+
Enter the value of a:
8
Enter the value of b:
8
The result of ab+ is = 16.000000   



_____________________http://sundcs.blogspot.com/_________________



//Program to convert Infix Expression to Postfix Expression

#include<stdio.h>
#include<conio.h>
#include<string.h>
char stack[50];
int top=-1;
void in_to_post(char infix[]);
void push(char);
char pop();
void main()
{
char infix[25];
clrscr();
printf("Enter the infix expression:\n");
gets(infix);
in_to_post(infix);
getch();
}
void push(char symb)
{
if(top>=49)
{
printf("Stack overflow");
getch();
return;
}
else
{
top=top+1;
stack[top]=symb;
}
}
char pop()
{
char item;
if(top==-1)
{
printf("Stack empty");
getch();
return(0);
}
else
{
item=stack[top];
top--;
}
return(item);
}
int preced(char ch)
{
if(ch==47)
{
return(5);
}
else if(ch==42)
{
return(4);
}
else if(ch==43)
{
return(3);
}
else
{
return(2);
}
}
void in_to_post(char infix[])
{
int length;
static int index=0,pos=0;
char symbol,temp;
char postfix[40];
length=strlen(infix);
push('#');
while(index<length)
{
symbol=infix[index];
switch(symbol)
{
case '(' : push(symbol);
break;
case ')' : temp=pop();
while(temp!='(')
{
postfix[pos]=temp;
pos++;
temp=pop();
}
break;
case '+' :
case '-' :
case '*' :
case '/' :
case '^' :
while(preced(stack[top])>=preced(symbol))
{
temp=pop();
postfix[pos]=temp;
pos++;
}
push(symbol);
break;
default : postfix[pos++]=symbol;
break;
}
index++;
}
while(top>0)
{
temp=pop();
postfix[pos++]=temp;
}
postfix[pos++]='\0';
printf("The postfix expression is:\n",postfix);
puts(postfix);
return;
}

--------------- OUTPUT -----------------


Enter the infix expression:
a + b
The postfix expression is:
ab+




_____________________http://sundcs.blogspot.com/_________________




 // Program to Implement Binary Search Tree


#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
typedef struct bst
{
int data;
struct bst *left, *right;
}node;
void insert(node *,node*);
void inorder(node*);
node *search(node *,int,node **);
void del(node *,int);
void main()
{
int ch;
char ans='N';
int key;
node *New,*root,*tmp,*parent;
node *get_node();
root=NULL;
clrscr();
printf("\n \t Program for Binary Search Tree");
do
{
printf("\n 1.Create \n 2. Search \n 3. Delete \n 4.Display");
printf("\n\n Enter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1 : do
{
New=get_node();
printf("\n Enter the Element");
scanf("%d",&New->data);
if(root==NULL)
root=New;
else
insert(root,New);
printf("\n Do u want to continue enter more elements(y/n)");
ans=getch();
}while(ans=='N');
break;
case 2: printf("/n Enter the element which u want to search");
scanf("%d",&key);
tmp=search(root,key,&parent);
printf("\n Parent of node %d is %d",tmp->data,parent->data);
break;
case 3: printf("\n Enter the Element u wish to delete");
scanf("%d",&key);
del(root,key);
break;
case 4: if(root==NULL)
printf("Tree is not created");
else
{
printf("\n The tree is:");
inorder(root);
}
break;
}
} while(ch!=5);
}
node *get_node()
{
node *temp;
temp=(node*)malloc(sizeof(node));
temp->left=NULL;
temp->right=NULL;
return temp;
}
void insert(node *root,node *New)
{
if(New->data<root->data)
{
if(root->left==NULL)
root->left=New;
else
insert(root->left,New);
}
if(New->data>root->data)
{
if(root->right==NULL)
root->right=New;
else
insert(root->right,New);
}
}
node *search(node *root,int key,node **parent)
{
node *temp;
temp=root;
while(temp!=NULL)
{
if(temp->data==key)
{
printf("\n The %d Element is present",temp->data);
return temp;
}
*parent=temp;
if(temp->data>key)
temp=temp->left;
else
temp=temp->right;
}
return NULL;
}
void del(node *root,int key)
{
node *temp,*parent,*temp_succ;
temp=search(root,key,&parent);
if(temp->left!=NULL && temp->right!=NULL)
{
parent=temp;
temp_succ=temp->right;
while(temp_succ->left!=NULL)
{
parent = temp_succ;
temp_succ=temp_succ->left;
}
temp->data=temp_succ->data;
parent->right=NULL;
printf("\n Now deleted it!");
return;
}
if(temp->left!=NULL && temp->right==NULL)
{
if(parent->left==temp)
parent->left=temp->left;
else
parent->right=temp->left;
temp=NULL;
free(temp);
printf("\n Now deleted if!");
return;
}
if(temp->left==NULL && temp->right!=NULL)
{
if(parent->left==temp)
parent->left=temp->right;
else
parent->right=temp->right;
temp=NULL;
free(temp);
printf("\n Now Deleted it!");
return;
}
if(temp->left==NULL &&temp->right==NULL)
{
if(parent->left==temp)
parent->left=NULL;
else
parent->right=NULL;
printf("\n Now Deleted it!");
return;
}
}
void inorder(node *temp)
{
if(temp!=NULL)
{
inorder(temp->left);
printf(" %d",temp->data);
inorder(temp->right);
}
}


--------------- OUTPUT ----------------

Program for Binary Search Tree
1.Create
2. Search
3. Delete
4.Display
Enter your choice1
Enter the Element10
Enter your choice1
Enter the Element8
Enter your choice1
Enter the Element9
Enter your choice 1
Enter the Element 7
Enter your choice1
Enter the Element15
Enter your choice1
Enter the Element13
Enter your choice 1
Enter the Element14
Enter your choice 1
Enter the Element12
Enter your choice1
Enter the Element16
Do u want to continue enter more elements(y/n)y
1.Create
2. Search
3. Delete
4.Display
Enter your choice4
The tree is:7 8 9 10 12 13 14 15 16
1.Create
2. Search
3. Delete
4.Display
Enter your choice2
Enter the element which u want to search 16
The 16 Element is present
Parent of node 16 is 15
1.Create
2. Search
3. Delete
4.Display
Enter your choice 3
Enter the Element u wish to delete 13
The 13 Element is present
Now deleted it!
1.Create
2. Search
3. Delete
4.Display
Enter your choice 4
The tree is: 7 8 9 10 12 14 15 16




_____________________http://sundcs.blogspot.com/_________________




//  Program to Implement Stack Using Templates

#include<iostream>
using namespace std;
  template <class t> 
class stack
{
 t *stackarray;
 int size; 
int top; 
public:  stack()  {
  size=10;
  stackarray=new t[size];
  top=-1;
 }
  ~stack()
  {
 delete []stackarray;
 } 
void push(t k);
  void pop();
  void print();
  int isempty();
 int isfull();
}
  template <class t>
 int stack<t>::isempty() {
  return(top==-1);
 } 
template <class t>
int stack<t>::isfull() { 
return (top==size);
 } 
template <class t>
 void stack<t>::push(t k) {
  stackarray[++top]=k;
 } 
template <class t>
 void stack<t>::pop() { 
top--;

template <class t>
 void stack<t>::print() { 
for(int i=0;i<=top;i++)
 { 
cout<<"\n"<<stackarray[i];
  }
}
  int main() { 
stack <int> s;
  cout<<"\nPushing elements 2,3,6...";
 if(!s.isfull()) 
{
  s.push(2);
 s.push(3);
 s.push(6);
 } 
cout<<"\nStack is...";
 s.print();
 cout<<"\nPoping..";
 if
(!s.isempty()) 
s.pop();
 cout<<"\nstack is...";
  s.print();
 cout<<endl;
 }




_____________________http://sundcs.blogspot.com/_________________



// Program to Implement File Handling

#include<stdio.h>
#include<conio.h>
#include<fstream.h>
#include<process.h>
class student
{
private:
char name[10];
char branch[10];
int id;
char semester[10];
public:
void getdata();
void saveinfile();
void readfromfile();
void display();
void search();
void deleted();
};
void student:: getdata()
{
cout<<"enter the name";
cin>>name;
cout<<"enter the branch";
cin>>branch;
cout<<"enter the semester";
cin>>semester;
cout<<"enter id";
cin>>id;
this->saveinfile();
} void student::saveinfile()
{
fstream obj;
obj.open("record.txt",ios::app);
obj.write((char*)this,sizeof(student));
obj.close();
}
void student::readfromfile()
{
fstream obj;
obj.open("record.txt",ios::in|ios::nocreate);
if(!obj.fail())
{
obj.read((char*)this,sizeof(student));
while(!obj.eof())
{
this->display();
obj.read((char*)this,sizeof(student));
}}
obj.close();
}
void student::display()
{
cout<<name<<endl;
cout<<branch<<endl;
cout<<semester<<endl;
cout<<id<<endl;
} void student::deleted()
{
int id2;
fstream obj,obj1;
cout<<"enter id to be deleted";
cin>>id2;
obj.open("record.txt",ios::in|ios::nocreate);
obj1.open("new.txt",ios::app);
obj.read((char*)this,sizeof(student));
while(!obj.eof())
{
if(this->id!=id2)
{
obj1.write((char*)this,sizeof(student));
}
obj.read((char*)this,sizeof(student));
}
remove("record.txt");
rename("new.txt","record.txt");
}
void student::search()
{
int id1;
fstream obj;
obj.open("record.txt",ios::in);
obj.read((char*)this,sizeof(student));
cout<<"enter the id to search";
cin>>id1;
while(!obj.eof())
{
if(this->id==id1)
{
cout<<endl<<"record is found"<<endl;
int l=obj.tellg();
obj.seekg(l- sizeof(student));
obj.read((char *)this,sizeof(student));
this->display();
break;
}
obj.read((char *)this,sizeof(student));
} obj.close();
} void main()
{
student s1;
clrscr();
int x;
while(1)
{
cout<<" MENU"<<endl;
cout<<"1..add,2..display,3..search,4..remove,5..exit"<<endl;
cout<<"enter your choice"<<endl;
cin>>x;
switch(x)
{
case 1:
s1.getdata();
break;
case 2:
s1.readfromfile();
break;
case 3:
s1.search();
break;
case 4:
s1.deleted();
break;
case 5:
exit(0);
}
}
}


_____________________http://sundcs.blogspot.com/_________________