Sie sind auf Seite 1von 114

Practical File Advanced Data Structures Using C++

Subject Code

Submitted To:
Silky Makker Assistant Prof. CSE Department

Submitted by:
Name Branch/Sem Roll No.:

ADVANCED DATA STRUCTURES USING C++ Lab. File

Department of Computer Science Application, Samalkha Group of Institution, Kurushetra University

INDEX
S. No. Program Name 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 2 Write a program in C++ to implement Linear Search. Write a program in C++ to implement Binary Search. Write a program in C++ to implement Insertion Sort. Write a program in C++ to implement Selection Sort. Write a program in C++ to implement Bubble Sort. Write a program in C++ to implement Quick Sort. Write a program in C++ to implement Merge Sort. Write a program in C++ to implement Heap Sort. Write a program in C++ to implement Stack using Linked List. Write a program in C++ to implement Stack using Array.
Write A Program in C++ to Convert Infix Expression To Postfix Expression Using Stack

Page No.

Date

Teachers Signature

Write a program in C++ to implement Queue using Linked List. Write a program in C++ to implement Queue using Array. Write a program in C++ to implement Circular Queue using Linked List. Write a program in C++ to implement Singly Linked
ADVANCED DATA STRUCTURES USING C++ Lab. File

List and its Operations 16 Write a program in C++ to implement Double Circular Linked List and its Operations.

INDEX
S. No. 17 Program Name Write a program to Implement Binary Search Tree 1. Insertion 2. Deletion 3. Finding an element 4. Min element 5. Max element 6. Left child 7. Right child 8. Recursive and Non recursive traversals ( In order, Preorder and Post order) 9. Finding the number of nodes, leaves, full nodes, ancestors, descendants Write a program in C++ To Implement a Binary tree 1. Create a tree 2. Mirror image of Tree 3. Finding height of Tree. Write a Progrsam in C++ to Implement a Graph Using Adjacency Matrix. Write a program in C++ to Implement Graph Using Adjacency List. Write a program in C++ to find DFS and BFS of a Graph. Page no. Date Teachers Signature

18

19 20 21

ADVANCED DATA STRUCTURES USING C++ Lab. File

SEARCHING & SORTING


4
ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement Linear Search. //


#include<iostream.h> #include<conio.h> int linear_search(int [],int,int); main() { clrscr(); constint array_size=10; int array[array_size]={0}; cout<<"\n Enter the contents of the array are : "<<endl; cout<<"\n Elements :"<<"\t\t Value:"<<endl;

for(int count=0;count<array_size;count++) { cout<<"\t"<<" array ["<<count<<"]"<<"\t\t"; cin>>array[count]; } int searching_element=0; int flag=0; cout<<"\n\n Enter the element you want to find = "; cin>>searching_element; flag=linear_search(array,array_size,searching_element); if(flag!=-1) cout<<"\n The given element is found at the position array["<< flag<<"]"<<endl; else

ADVANCED DATA STRUCTURES USING C++ Lab. File

cout<<"\n The given element is not found. "<<endl; getch(); return 0; } /*************************************************************************/// -------------------- linear_search(int [], int, int) ------------------///*************************************************************************/ int linear_search(int array[],int size, int element) { for(int count=0;count<size;count++) { if(element==array[count]) { return count; } } return -1; } Output

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement Binary Search //


#include<iostream.h> #include<conio.h> void binsearch(int ar[],int size,int ele) { int lb=0,ub=size-1,mid; //lb=>lower bound,ub=>upper bound for(;lb<ub;) { mid=(lb+ub)/2; if(ar[mid]==ele) { cout<<"\n SEARCH SUCCESSFUL"; break; } else if(ar[mid]<ele) ub=mid-1; else if(ar[mid]>ele) lb=mid+1; } if(ub<lb) cout<<"\n SEARCH UNSUCCESSFUL"; } void sort(int ar[],int size) //sorts the array in ascending array using bubble sort ADVANCED DATA STRUCTURES USING C++ Lab. File

{ int temp; for(int i=0;i<size;i++) for(int j=0;j<size-i-1;j++) if(ar[j]>ar[j+1]) { temp=ar[j]; ar[j]=ar[j+1]; ar[j+1]=temp; } } void display(int ar[],int size) { for(int i=0;i<size;i++) cout<<'\n'<<ar[i]; } void input(int ar[],int size) { for(int i=0;i<size;i++) cin>>ar[i]; } void main() { clrscr(); int size; cout<<"\n ENTER THE NUMBER OF ELEMENTS REQUIRED IN THE ARRAY :"; cin>>size; int *ar=new int(size); cout<<"\n ENTER THE ELEMENTS OF THE ARRAY :\n"; input(ar,size); sort(ar,size); //takes the input from the array //sorts the array in the ascending order

int ele; cout<<"\n ENTER THE ELEMENT TO BE FOUND :\n"; cin>>ele; getch(); }

ADVANCED DATA STRUCTURES USING C++ Lab. File

Output ENTER THE NUMBER OF ELEMENTS REQUIRED IN THE ARRAY: 6 ENTER THE ELEMENTS OF THE ARRAY: 22 33 45 67 78 90 ENTER THE ELEMENT TO BE FOUND: 67 SEARCH SUCCESSFUL

// Write a Program in C++ to implement Insertion sort //


#include <iostream> #include<conio.h> #define ELEMENTS 6 void insertion_sort(int x[],int length) { int key,i; for(int j=1;j<length;j++) { key=x[j]; i=j-1; while(x[i]>key && i>=0) { x[i+1]=x[i]; i--; } x[i+1]=key; } } int main() {

ADVANCED DATA STRUCTURES USING C++ Lab. File

int A[ELEMENTS]={5,2,4,6,1,3}; int x; cout<<"NON SORTED LIST:"<<endl; for(x=0;x<ELEMENTS;x++) { cout<<A[x]<<endl; } insertion_sort(A,ELEMENTS); cout<<endl<<"SORTED LIST"<<endl; for(x=0;x<ELEMENTS;x++) { cout<<A[x]<<endl; } return 0; } Output NON SORTED LIST: 5 2 4 6 1 3

SORTED LIST 1 2 3 4 5 6

10

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement Selection Sort // #include<iostream.h> #include<conio.h> class sort { int a[10]; public: void inputarr(int num); void display(int num); void selection(int num); }; void sort::inputarr(int num) { int i; cout<<"Enter the elements in the array"<<endl; for(i=0;i<num;i++) cin>>a[i]; } void sort::display(int num) {

11

ADVANCED DATA STRUCTURES USING C++ Lab. File

int i; for(i=0;i<num;i++) cout<<a[i]<<" "; cout<<endl; } void sort::selection(int num) { int i,j,t,l,m; for(i=0;i<num;i++) { m=a[i]; l=i; for(j=i+1;j<num;j++) { if(m>a[j]) { m=a[j]; l=j; } } t=a[i]; a[i]=a[l]; a[l]=t; } } void main() { int num,i; sort s1; cout<<" SELECTION SORT "<<endl; cout<<"Enter the number of elements"<<endl; cin>>num; s1.inputarr(num); cout<<"The numbers in the unsorted array are"<<endl; s1.display(num); s1.selection(num); cout<<"Array after selection sort is applied"<<endl; s1.display(num); getch(); } Output Enter the number of elements 4 Enter the elements in the array

12

ADVANCED DATA STRUCTURES USING C++ Lab. File

7 83 69 2 The numbers in the unsorted array are 7 83 69 2

Array after selection sort is applied 2 7 69 83

// Write a program in C++ to implement Bubble Sort // #include <iostream.h> #include <conio.h> #define MAX 10 class bubsort{ int arr[MAX],n; public: void getdata(); void showdata(); void sortLogic(); }; void bubsort :: getdata(){ cout<<"How many elements you require : ";

13

ADVANCED DATA STRUCTURES USING C++ Lab. File

cin>>n; for(int i=0;i<n;i++) cin>>arr[i]; } void bubsort :: showdata(){ cout<<"\n--Display--\n"; for(int i=0;i<n;i++) cout<<arr[i]<<" "; } void bubsort :: sortLogic(){ int temp; for(int i=0;i<n;i++){ for(int j=0,exchange=0;j<n;j++){ if(arr[j] > arr[j+1]){ temp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = temp; exchange++; cout<<"\n arr[j] = "<<arr[j]<<" arr[j+1] = "<<arr[j+1]; } } cout<<endl; if(exchange==0) break; } } void main(){ clrscr(); cout<<"\n*****Bubble Sort*****\n"; bubsort obj; obj.getdata(); obj.sortLogic(); obj.showdata(); getch(); } Output

14

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a Program in C++ to implement Merge Sort // #include <iostream.h> #include<conio.h> int a[50];

15

ADVANCED DATA STRUCTURES USING C++ Lab. File

void merge(int,int,int); void merge_sort(int low,int high) { int mid; if(low<high) { mid=(low+high)/2; merge_sort(low,mid); merge_sort(mid+1,high); merge(low,mid,high); } } void merge(int low,int mid,int high) { int h,i,j,b[50],k; h=low; i=low; j=mid+1; while((h<=mid)&&(j<=high)) { if(a[h]<=a[j]) { b[i]=a[h]; h++; } else { b[i]=a[j]; j++; } i++; } if(h>mid) { for(k=j;k<=high;k++) { b[i]=a[k]; i++; } } else { for(k=h;k<=mid;k++) { b[i]=a[k]; i++; }

16

ADVANCED DATA STRUCTURES USING C++ Lab. File

} for(k=low;k<=high;k++) a[k]=b[k]; } void main() { int num,i; cout<<"******************************************************************* *************"<<endl; cout<<" MERGE SORT PROGRAM"<<endl; cout<<"******************************************************************* *************"<<endl; cout<<endl<<endl; cout<<"Please Enter THE NUMBER OF ELEMENTS you want to sort:"<<endl; cin>>num; cout<<endl; cout<<" Enter the ELEMENTS:"<<endl; for(i=1;i<=num;i++) { cin>>a[i] ; } merge_sort(1,num); cout<<endl; cout<<"So, the sorted list (using MERGE SORT) will be :"<<endl; cout<<endl<<endl; for(i=1;i<=num;i++) cout<<a[i]<<" "; cout<<endl<<endl<<endl<<endl; }

Output Please Enter THE NUMBER OF ELEMENTS you want to sort : 5 Enter the ELEMENTS 3 8 90 67 54

So, the sorted list (using MERGE SORT) will be 3 8 54 67 90 ADVANCED DATA STRUCTURES USING C++ Lab. File

17

// Write a Program in C++ to Implement Quick Sort // #include<process.h> #include<iostream.h> #include<conio.h> #include<stdlib.h> int Partition(int low,int high,int arr[]); void Quick_sort(int low,int high,int arr[]); void main() {int *a,n,low,high,i; clrscr(); cout<<"/ **************************Quick Sort AlgorithmImplementation*****************/"; cout<<"Enter number of elements:"; cin>>n; a=new int[n]; cout<<"enter the elements:"; for(i=0;i<n;i++) cin>>a; for(i=0;i<n;i++) a[i]=rand()%100; clrscr(); cout<<"Initial Order of elements"; for(i=0;i<n;i++) cout<<a[i]<<" "; cout<<" "; high=n-1; low=0; Quick_sort(low,high,a); cout<<"Final Array After Sorting:"; for(i=0;i<n;i++) cout<<a[i]<<" "; getch(); } /*Function for partitioning the array*/ int Partition(int low,int high,int arr[]) { int i,high_vac,low_vac,pivot/*,itr*/; pivot=arr[low]; while(high>low) {

18

ADVANCED DATA STRUCTURES USING C++ Lab. File

high_vac=arr[high]; while(pivot<high_vac) { if(high<=low) break; high--; high_vac=arr[high]; } arr[low]=high_vac; low_vac=arr[low]; while(pivot>low_vac) { if(high<=low) break; low++; low_vac=arr[low]; } arr[high]=low_vac; } arr[low]=pivot; return low; } void Quick_sort(int low,int high,int arr[]) { int Piv_index,i; if(low<high) { Piv_index=Partition(low,high,arr); Quick_sort(low,Piv_index-1,arr); Quick_sort(Piv_index+1,high,arr); } } Output **************************Quick Sort Algorithm Implementation***************** Enter the number of elements : 7 Enter the elements 23 56 78 12 34 25 55

19

ADVANCED DATA STRUCTURES USING C++ Lab. File

Final order of elements after ordering: 12 23 25 34 55 56 78

// Write a Program in C++ to implement Heap Sort //

#include<iostream.h> #include<conio.h> //using namespace std; class Heap1 { int *heap; int heapsize; int arraysize; public : void maxHeapify(int); // maintains max-heap property int left(int a) // returns index of left child { return 2*a +1; } int right(int a) //returns index of right child { return (2*a +2); } int parent(int a) { if(a%2 != 0) return a/2; return a/2-1; } void buildMaxHeap(); // builds a heap void heapSort(); // sorts data }; void Heap1 :: heapSort() { buildMaxHeap(); // creates max heap for (int j=0;j<arraysize;j++) // generate max element in each pass { int temp = heap[0]; heap[0] = heap[heapsize-1];

20

ADVANCED DATA STRUCTURES USING C++ Lab. File

heap[heapsize-1] = temp; heapsize = heapsize-1; // and decrease the heap size maxHeapify(0); } cout << "Sorted List is : \n"; for( j=arraysize-1;j>=0;j--) { cout << endl << heap[j]; // displays the array } } void Heap1 :: buildMaxHeap() { int number; cout << "Enter no. of Elements"; cin >> arraysize; heap = new int[arraysize]; // declare array cout << "Enter Elements :"; for(int j=0;j<= arraysize-1;j++) // input elements { cin >> heap[j] ; } heapsize = arraysize ; for(int i= arraysize/2+1 ;i >=0 ;i--) maxHeapify(i); // call maxheapify to make heap } void Heap1 :: maxHeapify(int a ) // maintains the max heap property { int l,r,temp; int largest; l = left(a); r = right (a); if( (l <= heapsize-1) && (heap[l] > heap[a]) ) largest = l; else largest = a; if( (r <= heapsize-1) && (heap[r] > heap[largest]) ) largest = r; if (largest != a) {

21

ADVANCED DATA STRUCTURES USING C++ Lab. File

temp = heap[largest]; heap[largest] = heap[a]; heap[a] = temp; maxHeapify(largest); } } int main() { Heap1 h ; h.heapSort(); // call to heapsort getch(); return 0; }

22

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement Shell Sort //

#include< iostream.h> #include< conio.h> void shellsort(int a[],int n) { int j,i,k,m,mid; for(m = n/2;m>0;m/=2) { for(j = m;j< n;j++) { for(i=j-m;i>=0;i-=m) { if(a[i+m]>=a[i]) break; else { mid = a[i]; a[i] = a[i+m]; a[i+m] = mid; } } } }

23

ADVANCED DATA STRUCTURES USING C++ Lab. File

} int main() { int a[10],i,n; clrscr(); cout<< "Enter The number Of Elements\t: "; cin>>n; for(i=0;i< n;i++) { cout<<\nElement \t: "<<i+1; cin>>a[i]; } cout<<\nArray Befor Sorting : "; for(i=0;i< n;i++) cout<<a[i]; shellsort(a,n); cout<<"\nArray After Sorting : "; for(i=0;i< n;i++) cout<<a[i]; getch(); return 0; } Output Enter The number Of Elements : 5 Element 1 : 21 Element 2 : 36 Element 3 : 54

24

ADVANCED DATA STRUCTURES USING C++ Lab. File

Element 4 : 2 Element 5 : 0 Array Befor Sorting : 21 Array After Sorting : 0 36 2 54 21 2 36 0 54

// Write a program in C++ to implement Radix Sort //

#include < iostream.h> #include < conio.h> #include < stdlib.h> void radix(int a[],int n,int m) { typedef struct node { int data; struct node * next; }NODE; NODE * ptr,*start,*prev; NODE *front[10], *rear[10]; int k=1,i,j,y,p;; /*creating initial linked list*/ start=NULL; for(i=0;i< n;++i) { ptr=(NODE *)malloc(sizeof(NODE));

25

ADVANCED DATA STRUCTURES USING C++ Lab. File

ptr->data=a[i]; ptr->next=NULL; if(start==NULL) start=ptr; else prev->next=ptr; prev=ptr; } /*radix sort*/ for(i=1;i< =m;++i) { for(j=0;j< 10;++j) front[j]=NULL; /*placing elements into queues*/ ptr=start; while(ptr!=NULL) { y=ptr->data/k %10;/*y is the digit*/ if(front[y]==NULL) { front[y]=ptr; rear[y]=ptr; } else { rear[y]->next=ptr; rear[y]=ptr; } ptr=ptr->next; } start=NULL; for(j=0;j< 10;++j) if(front[j]!=NULL) { if(start==NULL) start=front[j]; else rear[p]->next=front[j];

26

ADVANCED DATA STRUCTURES USING C++ Lab. File

p=j; } rear[p]->next=NULL; k=k*10; } /*copying back to array*/ ptr=start; for(i=0;i< n;++i,ptr=ptr->next) a[i]=ptr->data; } void main() { int a[100],n,i,m; char temp; do { clrscr(); cout<< "========================RADIX SORT====================<<endl; cout<<"ENTER NUMBER OF NUMBERS AND NUMBER OF DIGITS"<<endl; cin>>n>>m; cout<<ENTER ELEMENTS"<<endl; for(i=0;i< n;++i) cin>> a[i]; radix(a,n,m); cout<<SORTED LIST<<endl; for(i=0;i< n;++i) cout<<a[i]; cout<< "DO YOU wish to continue?[y/n]"<<endl; cin>>temp;

}while(temp=='y'|| temp=='Y'); cout<<"-------------------------------------------------------------------------------"; getch(); } Output =======================RADIX SORT=========================

27

ADVANCED DATA STRUCTURES USING C++ Lab. File

Enter number of numbers and number of digits 4 2 Enter elements 25 65 35 45 Sorted list: 25 35

45

65

Do you wish to continue?[y/n] n

28

ADVANCED DATA STRUCTURES USING C++ Lab. File

ABSTRACT DATA TYPES


// Write a program to Implement stack and its operations using linked list //

#include <iostream.h> #include<conio.h>

29

ADVANCED DATA STRUCTURES USING C++ Lab. File

using namespace std; struct node { int val; node *nxt; }; class stack { node *top; public: stack() { top=NULL; } void push(int el) { node *tmp = new node; tmp->val = el; tmp->nxt = top; top = tmp; } int pop() { if(top == NULL) { cout << "Stack Underflow\n"; return -1; } node *tmp = top; int el = top->val; top = top->nxt; delete tmp; return el; } void display() { if(top==NULL) { cout<<"stack empty\n"; return;

30

ADVANCED DATA STRUCTURES USING C++ Lab. File

} for (node *tmp = top; tmp!=NULL; tmp=tmp->nxt) { cout << "|\t" << tmp->val << "\t|" <<endl; } cout << "------------------"; } ~stack() { delete top; } }; int main() { stack a; while (1) { cout << "\nOptions:\n"; cout << "1.Push..\n" << "2.Pop..\n" << "3.Display..\n" << "4.Exit.\n"; cout << "Enter your choice....\n"; int ch; cin >> ch; switch (ch) { case 1: cout << "Enter the element to push..\n"; int el; cin >> el; a.push(el); break; case 2: el=a.pop(); if(el!=-1) cout << "Element popped is: " << el; break; case 3: a.display();

31

ADVANCED DATA STRUCTURES USING C++ Lab. File

break; case 4: return 0; } cin.get(); } }

// Write a program in C++ to Implement stack using array //

32

ADVANCED DATA STRUCTURES USING C++ Lab. File

#include <iostream> //#include <conio.h> const int SIZE=3; using namespace std; class stack { int arr[SIZE]; int top; public: stack() { top = -1; } void push(int ele) { if (top==SIZE-1) { cout<<"stack overflow\n"; return; } arr[++top] = ele; } int pop() { if(top==-1) { cout<<"stack underflow\n"; return -1; } return(arr[top--]); } void display() { if(top==-1) { cout<<"stack empty\n"; return;

33

ADVANCED DATA STRUCTURES USING C++ Lab. File

} cout << endl; for(int i=top; i>=0; i--) { cout << "|\t" << arr[i] << "\t|" <<endl; } cout << "------------------"; } }; int main() { stack a; while (1) { cout << "\nOptions:\n"; cout << "1.Push..\n" << "2.Pop..\n" << "3.Display..\n" << "4.Exit.\n"; cout << "Enter your choice....\n"; int ch; cin >> ch; switch (ch) { case 1: cout << "Enter the element to push..\n"; int el; cin >> el; a.push(el); break; case 2: el=a.pop(); if(el!=-1) cout << "Element popped is: " << el; break; case 3: a.display(); break; case 4: return 0; }

34

ADVANCED DATA STRUCTURES USING C++ Lab. File

cin.get(); } }

35

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to Convert Infix Expression To Postfix Expression Using Stack // #include <iostream.h> #include <string.h> #include <ctype.h> #include <conio.h> const int SIZE = 50; class stack { char stk[SIZE]; int top; public: stack() { top = -1; } char topele() { return (stk[top]); } void push(char c) { stk[++top] = c; } char pop() { return stk[top--]; } };

class infix : private stack { char *expr;

36

ADVANCED DATA STRUCTURES USING C++ Lab. File

public: infix() { expr = NULL; } void setexpr(char*); char* convertToPrefix(); char* convertToPostfix(); int priority(char c); ~infix() { cout << "Inside destructor"; delete expr; } };

void infix :: setexpr(char* s) { expr = new char[strlen(s)+1]; strcpy(expr,s); cin.get(); } char* infix :: convertToPrefix() { char *s = new char[strlen(expr)+2]; strcpy(s,expr); int l = strlen(s); strrev(s); s[l] = '('; s[l+1] = '\0'; push(')'); //char t[50]; char *t = new char[50]; // int j; for (int i=0, j=0; s[i]!=0; i++) { if (s[i] == ' ') { continue; }

37

ADVANCED DATA STRUCTURES USING C++ Lab. File

if (isdigit(s[i])) { t[j++] = s[i]; //cin.get(); } else if (s[i] == ')') { push(s[i]); } else if (s[i] == '(') { char c = pop(); while (c != ')') { t[j++] = c; c = pop(); } } else { char c = topele(); while (priority(c) > priority(s[i])) { t[j++] = pop(); c = topele(); } push(s[i]); } t[j] = 0; } cin.get(); strrev(t); return (t); } int infix :: priority(char c) { switch (c) { case '^': return 3; case '/':

38

ADVANCED DATA STRUCTURES USING C++ Lab. File

case '*': return 2; case '+': case '-': return 1; default: return 0; } } char* infix :: convertToPostfix() { char *s = new char[strlen(expr)+2]; strcpy(s,expr); int l = strlen(s); //strrev(s); s[l] = ')'; s[l+1] = '\0'; push('('); //char t[50]; char *t = new char[50]; for (int i=0,j=0; s[i]; i++) { if (s[i] == ' ') { continue; } if (isdigit(s[i])) { t[j++] = s[i]; //cin.get(); } else if (s[i] == '(') { push(s[i]); } else if (s[i] == ')') { char c = pop(); while (c != '(') { t[j++] = c;

39

ADVANCED DATA STRUCTURES USING C++ Lab. File

c = pop(); } } else { char c = topele(); while (priority(c) > priority(s[i])) { t[j++] = pop(); c = topele(); } push(s[i]); } t[j] = 0; } cin.get(); return (t); } int main() { clrscr(); if(1) { infix exp; cout << "Enter the Infix Expression.." << endl; char str[50]; cin.getline(str,50); cin.get(); exp.setexpr(str); char *s = exp.convertToPrefix(); cin.get(); cout << "Equivalent Prefix Expression...................\n" << s; s = exp.convertToPostfix(); cin.get(); cout << "Equivalent Postfix Expression...................\n" << s; cin.get(); } return 0;

40

ADVANCED DATA STRUCTURES USING C++ Lab. File

41

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement Queue & its Operations Using Linked List // #include <iostream.h> #include <conio.h> #include <stdlib.h> struct node { char name[20]; int age; float height; node *nxt; }; node *start_ptr=NULL; int main() { void push (); void pop(); char ch; clrscr(); cout<<"Queue"; cout<<"-----"; do { cout<<"Select an operation"; cout<<"u->push"; cout<<"o->pop"; cout<<"e->exit"; cin>>ch; switch(ch) { case 'u': push(); break; case 'o': pop(); break; case 'e':

42

ADVANCED DATA STRUCTURES USING C++ Lab. File

exit(0); } } while(ch!='e'); return 0; } void pop() { node *temp1,*temp2; if(start_ptr==NULL) cout<<"The list is empty"; else { temp1=start_ptr; temp2=temp1; while(temp1->nxt!=NULL) { temp2=temp1; temp1=temp1->nxt; } if(temp1==temp2) { cout<<temp1->name<<","; cout<<temp1->age<<", "; cout<<temp1->height; start_ptr=NULL; } else { cout<<temp1->name<<", "; cout<<temp1->age<<", "; cout<<temp1->height; temp2->nxt=NULL; delete temp1; } } } void push () { node *temp; temp = new node; cout << "Please enter the name of the person: ";

43

ADVANCED DATA STRUCTURES USING C++ Lab. File

cin >> temp->name; cout << "Please enter the age of the person: "; cin >> temp->age; cout << "Please enter the height of the person: "; cin >> temp->height; if (start_ptr == NULL) { temp->nxt=NULL; start_ptr = temp; } else { temp->nxt=start_ptr; start_ptr=temp; } }

44

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement Queue using array // # include<iostream.h> # include<conio.h> # define SIZE 20 class queue { int a[SIZE]; int front; int rear; public: queue(); ~queue(); void insert(int i); int remove(); int isempty(); int isfull(); }; queue::queue() { front=0; rear=0; } queue::~queue() { delete []a; } void queue::insert(int i) { if(isfull()) { cout<<"******Queue is FULL !!!

45

ADVANCED DATA STRUCTURES USING C++ Lab. File

No insertion allowed further. ******"; return; } a[rear] = i; rear++; } int queue::remove() { if(isempty()) { cout<<"******Queue Empty !!! Value returned will be garbage. ******"; return (-9999); } return(a[front++]); } int queue::isempty() { if(front == rear) return 1; else return 0; } int queue::isfull() { if(rear == SIZE) return 1; else return 0; } void main() { clrscr(); queue q; q.insert(1); q.insert(2); cout<<" "<<q.remove(); cout<<" "<<q.remove(); cout<<" "<<q.remove(); getch();

46

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a Program in C++ to Implement Cicular Queue using Array // #include<iostream.h> #include<conio.h> const int MAX = 5; class cqueue { int a[MAX],front,rear; public : cqueue() { front=rear=-1; } void insert(int ); int deletion(); void display(); }; void cqueue :: insert(int val) { if((front==0 && rear==MAX-1) || (rear+1==front)) cout<<" Circular Queue is Full"; else { if(rear==MAX-1) rear=0; else

47

ADVANCED DATA STRUCTURES USING C++ Lab. File

rear++; a[rear]=val; } if(front==-1) front=0; } int cqueue :: deletion() { int k; if(front==-1) cout<<"Circular Queue is Empty"; else { k=a[front]; if(front==rear) front=rear=-1; else { if(front==MAX-1) front=0; else front++; } } return k; } void cqueue :: display() { int i; if(front==-1) cout<<"Circular Queue is Empty"; else { if(rear < front) { for(i=front;i<=MAX-1;i++) cout<<a[i]<<" "; for(i=0;i<=rear;i++) cout<<a[i]<<" "; } else { for(i=front;i<=rear;i++) cout<<a[i]<<" "; cout<<endl; } } }

48

ADVANCED DATA STRUCTURES USING C++ Lab. File

void main() { cqueue c1; int ch,val; char op; do { clrscr(); cout<<"-----------Menu-------------"; cout<<" 1.Insertion 2.Deletion 3.Display 4.Exit"; cout<<"Enter Your Choice <1..4> ?"; cin>>ch; switch(ch) { case 1 : cout<<"Enter Element to Insert ?"; cin>>val; c1.insert(val); break; case 2 : val=c1.deletion(); cout<<"Deleted Element :"<<val<<endl; break; case 3 : c1.display(); break; } cout<<"Do you want to continue<Y/N> ?"; cin>>op; }while(op=='Y' || op=='y'); getch(); } }

49

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to Implement single linked list and Operations. // 1. Insertion 2. Deletion at the Beginning, end & middle of List 3. Reverse the List

#include <iostream.h> #include <conio.h> struct node { int data; node *next; }; class LinkedList {

50

ADVANCED DATA STRUCTURES USING C++ Lab. File

node *start; public: LinkedList(){ start = NULL; void insertAtEnd(int); void insertAtBeg(int); void insertAfter(int, int); void traverseList(); void delItem(int); void delAfter(int); void reverse(); };

void LinkedList :: traverseList() { node *ptr = start;i if (ptr == NULL) { cout << "NULL"; } else { while (ptr->next != NULL) { cout << ptr->data << "-->"; ptr = ptr->next; } cout << ptr->data; } } void LinkedList :: insertAtBeg(int val) { node *tmp = new node; tmp->data = val; tmp->next = start; start = tmp; } void LinkedList :: insertAtEnd(int val) { node *tmp = new node;

51

ADVANCED DATA STRUCTURES USING C++ Lab. File

tmp->data = val; tmp->next = NULL; if (start == NULL) { start = tmp; } else { node *ptr = start; while (ptr->next != NULL) { ptr = ptr->next; } ptr->next = tmp; } } void LinkedList :: delItem(int val) { if (start == NULL) { cout << "List Empty..."; return; } node *ptr = start, *previous = start; while (ptr->data != val) { previous = ptr; ptr = ptr->next; if (ptr == NULL) { cout << "Node not in the List.."; return; } } if (previous == ptr) { start = ptr->next; } else { previous->next = ptr->next;

52

ADVANCED DATA STRUCTURES USING C++ Lab. File

} cout << "Node Removed.. " << ptr->data; //cout << start ;//<< " " << start->data << " " << start->next; delete ptr; //previous = NULL; } void LinkedList :: delAfter(int locVal) { node *ptr = start; while (ptr->data != locVal) { ptr = ptr->next; if (ptr == NULL) { cout << "Given Node not in the List.."; return; } } if (ptr->next == NULL) { cout << "No node to remove.."; return; } node *tmp = ptr->next; ptr->next = tmp->next; cout << "Node Removed.. " << tmp->data; delete tmp; } void LinkedList :: reverse() { LinkedList tmp; node *ptr = start; while (ptr != NULL) { tmp.insertAtBeg(ptr->data); ptr = ptr->next; } *this = tmp; }

53

ADVANCED DATA STRUCTURES USING C++ Lab. File

void LinkedList :: insertAfter(int locVal, int val) { if (start == NULL) { cout << "List Empty..."; return; } node *ptr = start; while (ptr->data != locVal) { ptr = ptr->next; if (ptr == NULL) { cout << "Given node not in the List.."; return; } } node *tmp = new node; tmp->data = val; tmp->next = ptr->next; ptr->next = tmp; } int main() { clrscr(); LinkedList l; while(1) { cout << "\n\nOperations on Linked List:"<< endl //<< "***Create List...1." << endl << "***Traverse the List.......1." << endl << "***Insert a node..." << endl << "*****At the beginning......2." << endl << "*****At the end............3." <<endl << "*****After a given node....4" << endl << "***Delete a node.." << endl << "*****For a given value.....5." << endl << "*****After a given node....6." << endl << "***Reverse the list........7." << endl

54

ADVANCED DATA STRUCTURES USING C++ Lab. File

<< "***Exit the program........8." << endl; cout << "Enter your choice...\t"; int ch; cin >> ch; switch (ch) { case 1: l.traverseList(); break; case 2: cout << "Enter the value to insert..\t"; int val; cin >> val; l.insertAtBeg(val); cout << "1 Node added.."; break; case 3: cout << "Enter the value to insert..\t"; //int val; cin >> val; l.insertAtEnd(val); cout << "1 Node added.."; break; case 4: cout << "Enter the value,,after which node is to be inserted..\t"; int locVal; cin >> locVal; cout << "Enter the value to insert..\t"; cin >> val; l.insertAfter(locVal,val); cout << "1 Node added.."; break; case 5: cout << "Enter the value to remove..\t"; cin >> val; l.delItem(val); break; case 6: cout << "Enter the value of node preeding the node to be removed..\t"; cin >> val; l.delAfter(val); break;

55

ADVANCED DATA STRUCTURES USING C++ Lab. File

case 7: l.reverse(); l.traverseList(); break; case 8: return 0; } } }

56

ADVANCED DATA STRUCTURES USING C++ Lab. File

57

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement Double Circular Linked list and its operations. // 1. Creation 2. Insertion 3. Deletion #include<iostream.h> #include<conio.h> class cirdlink { struct node { int data; node *rnext; node *lnext; }*new1,*head,*tail,*ptr,*temp; public: cirdlink() { head=tail=NULL; } void creation(); void insertion(); void deletion(); void display(); }; void cirdlink :: creation() { if(head==NULL) { new1=new node[sizeof(node)]; new1->rnext=NULL; new1->lnext=NULL; cout<<"enter student number :"; cin>>new1->data; head=new1; tail=new1; head->rnext=tail; head->lnext=tail; tail->rnext=head; tail->lnext=head; }

58

ADVANCED DATA STRUCTURES USING C++ Lab. File

else cout<<" creation done only once !"; } void cirdlink :: insertion() { int i,pos; new1=new node[sizeof(node)]; new1->rnext=NULL; new1->lnext=NULL; cout<<"enter student number :"; cin>>new1->data; cout<<"enter position you want to insert :"; cin>>pos; if(pos==1) { new1->rnext=head; head=new1; tail->lnext=head; tail->rnext=head; head->lnext=tail; } else { i=1; temp=head; while(i < pos-1 && temp->rnext!=tail) { i++; temp=temp->rnext; } if(temp->rnext==tail) { new1->rnext=tail->rnext; tail->rnext=new1; new1->lnext=tail; tail=new1; head->lnext=tail; } else { new1->rnext=temp->rnext; new1->lnext=temp; temp->rnext=new1; new1->rnext->lnext=new1; } } }

59

ADVANCED DATA STRUCTURES USING C++ Lab. File

void cirdlink :: deletion() { int pos,i; cout<<"Enter Position you want to Delete ?"; cin>>pos; if(pos==1 && head!=tail) { ptr=head; head=head->rnext; head->lnext=tail; tail->rnext=head; delete ptr; } else { i=1; temp=head; while(i < pos-1 && temp->rnext!=tail) { i++; temp=temp->rnext; } if(temp->rnext!=tail) { ptr=temp->rnext; temp->rnext=ptr->rnext; ptr->rnext->lnext=ptr->lnext; delete ptr; } else { if(temp->rnext==tail && head!=tail) { ptr=tail; tail=temp; tail->rnext=head; head->lnext=tail; delete ptr; } else { head=NULL; tail=NULL; delete head; delete tail; }

60

ADVANCED DATA STRUCTURES USING C++ Lab. File

} } } void cirdlink::display() { int ch; cout<<"1.forward 2.backward:"; cout<<"Enter your choice<1/2>?"; cin>>ch; switch(ch) { case 1: if(head!=NULL) { temp=head; while(temp!=tail) { cout<<temp->data<<" "; temp=temp->rnext; } if(temp==tail) cout<<temp->data; } break; case 2 : if(tail!=NULL) { temp=tail; while(temp!=head) { cout<<temp->data<<" "; temp=temp->lnext; } if(temp==head) cout<<temp->data; } break; } } void main() { cirdlink c1; int ch; char op; do {

61

ADVANCED DATA STRUCTURES USING C++ Lab. File

clrscr(); cout<<"----------Menu------------"; cout<<"1.Creation 2.Insertion 3.Deletion 4.Display"; cout<<"Enter Your choice <1..4> ?"; cin>>ch; switch(ch) { case 1 : c1.creation(); break; case 2 : c1.insertion(); break; case 3 :c1.deletion(); break; case 4 :c1.display(); break; } cout<<"Do you want to continue <Y/N> ?"; cin>>op; }while(op=='y' || op=='Y'); getch(); }

62

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement Priorty Queue //

#include <iostream.h> #include<conio.h> #include "PriorityQ.h" using namespace std; class PriorityQueue { struct node { int data; int priority; node *next; }*start; public: PriorityQueue() { start = NULL; } void insert(int, int); void del(); void traverse(); };

63

ADVANCED DATA STRUCTURES USING C++ Lab. File

// class implementation #include "PriorityQ.h" #include <iostream> using namespace std; void PriorityQueue :: insert(int val, int pr) { node *temp = new node; temp->data = val; temp->priority = pr; if (start == NULL) { start = temp; temp->next = NULL; return; } node *ptr = start , *previous = NULL; while (ptr->priority <= pr) { previous = ptr; ptr = ptr->next; if (ptr == NULL) break; } if (previous == NULL) { temp->next = start; start = temp; } else { temp->next = previous->next; previous->next = temp; } } void PriorityQueue :: del() { if (start == NULL) { cout << "Queue Empty..";

64

ADVANCED DATA STRUCTURES USING C++ Lab. File

return ; } cout << "Node Deleted...with value: "<< start->data << " and priority: " << start->priority; start = start->next; } void PriorityQueue :: traverse() { if (start == NULL) { cout << "Queue Empty"; return; } node *ptr; for ( ptr = start; ptr->next != NULL; ptr = ptr->next) { cout << "( " << ptr->data << " , " << ptr->priority << " )-->"; } cout << "( " << ptr->data << " , " << ptr->priority << " )"; } // main function int main() { PriorityQueue PQ; while (1) { cout << "\n\n-------------------------------------\n" << "Opertaions on Priority Queue..\n\n"; cout << "***Insert into Queue...1.\n\n" << "***Delete from Queue...2.\n\n" << "***Traverse the Queue..3.\n\n" << "***Exit................4.\n\n"; cout << "Enter your choice..\t"; int ch; cin >> ch; switch (ch) {

65

ADVANCED DATA STRUCTURES USING C++ Lab. File

case 1: cout << "Enter the value to insert..\t"; int val; cin >> val; cout << "Enter the priority..\t"; int pr; cin >> pr; PQ.insert(val,pr); cout << "One Node Added...."; break; case 2: PQ.del(); break; case 3: PQ.traverse(); break; case 4: return 0; } cin.get(); } return 0; }

66

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program to implement TOWER OF HANOI as an application of Recursion //

67

ADVANCED DATA STRUCTURES USING C++ Lab. File

#include<iostream> #include<cstdio.h> #include<cstdlib.h> using namespace std;

//the c++ standard library for stream input output //the c standard library for standard input output //for the exit function

class arr //arr class that holds each stag { public: int a[100],b[100],c[100]; int topa,topb,topc; }hanoi; int move=1; //counts the no. of moves int main() { void tower(int ,int *,int *,int *,int *,int *,int *); //function prototype void show(int); //function prototype int i; system("clear"); cout<<"Enter the no of elements for which u want to solve the problem"; scanf("%d",&i); system("clear"); for(int j=0;j<i;j++) //feeds the elements in the arrs; { hanoi.a[j]=j+1; hanoi.b[j]=-1; hanoi.c[j]=-1; } hanoi.topa=i-1; //topa,topb,topc,mean the top of each arr hanoi.topb=-1; hanoi.topc=-1; cout<<" Initially "<<" "; for(int j=i-1;j>-1;j--) //show the statusm of each arr { show(hanoi.a[j]); show(hanoi.b[j]); show(hanoi.c[j]); cout<<" "; } cout<<" "; tower(i,hanoi.a,hanoi.c,hanoi.b,&(hanoi.topa),&(hanoi.topc),&(hanoi.topb)); } void tower(int n,int src[],int dest[],int aux[],int *ts,int *td,int *ta) { pointers void show (int); //call to do the job //the tower function passes //the arrs along with the top

68

ADVANCED DATA STRUCTURES USING C++ Lab. File

if(n==1) { arr, dest[++(*td)]=src[(*ts)]; src[*ts]=-1; (*ts)--; int max; max=((*ts)>(*td)?(*ts):(*td)); max=(max>(*ta)?max:(*ta)); cout<<" Move "<<move++<<" "; for(int i=max;i>-1;i--) { show(hanoi.a[i]); show(hanoi.b[i]); show(hanoi.c[i]); cout<<" "; } cout<<" "; return; } tower(n-1,src,aux,dest,ts,ta,td); tower(1,src,dest,aux,ts,td,ta); tower(n-1,aux,dest,src,ta,td,ts); } void show(int a) { if(a==-1) cout<<"else cout<<a<<" }

//if one element is there in source arr , //then it is moved to the destination

//status of arrs shown

//else the //problem is solved by //recursive calls

//the show function shows the current status of the arrs "; ";

69

ADVANCED DATA STRUCTURES USING C++ Lab. File

TREES

70

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program to Implement Binary Search Tree // 1. Insertion 2. Deletion 3. Finding an element 4. Min element, Max element, 5. Left child, Right child, 6. Recursive (Top to Bottom left to Right) 7. Mon-recursive traversals (In order, Pre Order & Post order) 8. Finding the number of nodes, leaves, full nodes, ancestors, descendants
# include <conio.h> # include <process.h> # include <iostream.h> # include <alloc.h> struct node { int ele; node *left; node *right; }; typedef struct node *nodeptr; static int nodes=0; static int leaves=0; static int full=0; class stack { private: struct snode { nodeptr ele; snode *next; }; snode *top; public: stack() { top=NULL; } void push(nodeptr p) { snode *temp; temp = new snode;

71

ADVANCED DATA STRUCTURES USING C++ Lab. File

temp->ele = p; temp->next = top; top=temp; } void pop() { if (top != NULL) { nodeptr t; snode *temp; temp = top; top=temp->next; delete temp; } } nodeptr topele() { if (top !=NULL) return top->ele; else return NULL; } int isempty() { return ((top == NULL) ? 1 : 0); } }; class bstree { public: void insert(int,nodeptr &); void del(int,nodeptr &); int deletemin(nodeptr &); void find(int,nodeptr &); nodeptr findmin(nodeptr); nodeptr findmax(nodeptr); void copy(nodeptr &,nodeptr &); void makeempty(nodeptr &); nodeptr nodecopy(nodeptr &); void nonodes(nodeptr); void fullnodes(nodeptr); void ances(int,nodeptr &);

72

ADVANCED DATA STRUCTURES USING C++ Lab. File

void desc(int,nodeptr &); void allleaves(nodeptr); void noleaves(nodeptr); void preorder(nodeptr); void inorder(nodeptr); void postorder(nodeptr); void preordernr(nodeptr); void inordernr(nodeptr); void postordernr(nodeptr); void leftchild(int,nodeptr &); void rightchild(int,nodeptr &); }; void bstree::insert(int x,nodeptr &p) { if (p==NULL) { p = new node; p->ele=x; p->left=NULL; p->right=NULL; } else { if (x < p->ele) insert(x,p->left); else if (x>p->ele) insert(x,p->right); else cout<<"Element already Exits !"; } } void bstree:: del(int x,nodeptr &p) { nodeptr d; if (p==NULL) cout<<"Element not found "; else if (x < p->ele) del(x,p->left); else if (x > p->ele) del(x,p->right); else if ((p->left == NULL) && (p->right ==NULL)) { d=p; free(d); p=NULL; }

73

ADVANCED DATA STRUCTURES USING C++ Lab. File

else if (p->left == NULL) { d=p; free(d); p=p->right; } else if (p->right ==NULL) { d=p; p=p->left; free(d); } else p->ele=deletemin(p->right); } int bstree::deletemin(nodeptr &p) { int c; if (p->left == NULL) { c=p->ele; p=p->right; return c; } else c=deletemin(p->left); return c; } void bstree::copy(nodeptr &p,nodeptr &p1) { makeempty(p1); p1=nodecopy(p); } void bstree::makeempty(nodeptr &p) { nodeptr d; if (p!=NULL) { makeempty(p->left); makeempty(p->right); d=p; free(d); p=NULL; } }

74

ADVANCED DATA STRUCTURES USING C++ Lab. File

nodeptr bstree::nodecopy(nodeptr &p) { nodeptr temp; if (p == NULL) return p; else { temp = new node; temp->ele=p->ele; temp->left = nodecopy(p->left); temp->right = nodecopy(p->right); return temp; } } nodeptr bstree::findmin(nodeptr p) { if (p==NULL) { cout<<"Tree is empty !"; return p; } else { while (p->left !=NULL) p=p->left; return p; } }

nodeptr bstree::findmax(nodeptr p) { if (p==NULL) { cout<<"Tree is empty !"; return p; } else { while (p->right !=NULL) p=p->right; return p; } }

75

ADVANCED DATA STRUCTURES USING C++ Lab. File

void bstree::find(int x,nodeptr &p) { if (p==NULL) cout<<"Element not found !"; else { if (x <p->ele) find(x,p->left); else if ( x> p->ele) find(x,p->right); else cout<<"Element Found !"; } } void bstree::desc(int x,nodeptr &p) { if (p==NULL) cout<<"Element not found !"; else { if (x <p->ele) desc(x,p->left); else if ( x> p->ele) desc(x,p->right); else { if (p->left !=NULL) preorder(p->left); else preorder(p->right); } //cout<<"Element Found !"; } } void bstree::ances(int x,nodeptr &p) { if (p==NULL) cout<<"Element not found !"; else { if (x <p->ele) { cout<<p->ele<<"-->"; ances(x,p->left); } else if ( x> p->ele)

76

ADVANCED DATA STRUCTURES USING C++ Lab. File

{ cout<<p->ele<<"-->"; ances(x,p->right); } else cout<<"Element Found !"; } } void bstree::nonodes(nodeptr p) { if (p!=NULL) { nodes++; nonodes(p->left); nonodes(p->right); } } void bstree::noleaves(nodeptr p) { if (p!=NULL) { noleaves(p->left); if ((p->left == NULL) && (p->right == NULL)) leaves++; noleaves(p->right); } } void bstree::allleaves(nodeptr p) { if (p!=NULL) { allleaves(p->left); if ((p->left == NULL) && (p->right == NULL)) cout<<p->ele<<"-->"; allleaves(p->right); } } void bstree::fullnodes(nodeptr p) { if (p!=NULL) { fullnodes(p->left); if ((p->left != NULL) && (p->right != NULL)) full++; fullnodes(p->right); }

77

ADVANCED DATA STRUCTURES USING C++ Lab. File

} void bstree::preorder(nodeptr p) { if (p!=NULL) { cout<<p->ele<<"-->"; preorder(p->left); preorder(p->right); } } void bstree::inorder(nodeptr p) { if (p!=NULL) { inorder(p->left); cout<<p->ele<<"-->"; inorder(p->right); } } void bstree::postorder(nodeptr p) { if (p!=NULL) { postorder(p->left); postorder(p->right); cout<<p->ele<<"-->"; } } void bstree::preordernr(nodeptr p) { stack s; while (1) { if (p != NULL) { cout<<p->ele<<"-->"; s.push(p); p=p->left; } else if (s.isempty()) { cout<<"Stack is empty"; return;

78

ADVANCED DATA STRUCTURES USING C++ Lab. File

} else { nodeptr t; t=s.topele(); p=t->right; s.pop(); } } } void bstree::inordernr(nodeptr p) { stack s; while (1) { if (p != NULL) { s.push(p); p=p->left; } else { if (s.isempty()) { cout<<"Stack is empty"; return; } else { p=s.topele(); cout<<p->ele<<"-->"; } s.pop(); p=p->right; } } } void bstree::postordernr(nodeptr p) { stack s; while (1) { if (p != NULL) {

79

ADVANCED DATA STRUCTURES USING C++ Lab. File

s.push(p); p=p->left; } else { if (s.isempty()) { cout<<"Stack is empty"; return; } else if (s.topele()->right == NULL) { p=s.topele(); s.pop(); cout<<p->ele<<"-->"; if (p==s.topele()->right) { cout<<s.topele()->ele<<"-->"; s.pop(); } if (!s.isempty()) p=s.topele()->right; else p=NULL; } } } } void bstree::leftchild(int q,nodeptr &p) { if (p==NULL) cout<<"The node does not exists "; else if (q < p->ele ) leftchild(q,p->left); else if (q > p->ele) leftchild(q,p->right); else if (q == p->ele) { if (p->left != NULL) cout<<"Left child of "<<q<<"is "<<p->left->ele; else cout<<"No Left child !"; }

80

ADVANCED DATA STRUCTURES USING C++ Lab. File

} void bstree::rightchild(int q,nodeptr &p) { if (p==NULL) cout<<"The node does not exists "; else if (q < p->ele ) rightchild(q,p->left); else if (q > p->ele) rightchild(q,p->right); else if (q == p->ele) { if (p->right != NULL) cout<<"Right child of "<<q<<"is "<<p->right->ele; else cout<<"No Right Child !"; } } int main() { int ch,x,leftele,rightele; bstree bst; char c='y'; nodeptr root,root1,min,max; root=NULL; root1=NULL; do { // system("clear"); clrscr(); cout<<"Binary Search Tree"; cout<<"-------------------"; cout<<"1.Insertion 2.Deletion 3.NodeCopy"; cout<< 4.Find 5.Findmax 6.Findmin"; cout<<"7.Preorder 8.Inorder 9.Postorder"; cout<<"10.Leftchild 11.Rightchild 12.Counting";

81

ADVANCED DATA STRUCTURES USING C++ Lab. File

cout<<"Enter your choice :"; cin>>ch; switch(ch) { case 1: cout<<"1.Insertion"; cout<<"Node Element ?"; cin>>x; bst.insert(x,root); cout<<"Inorder traversal is :"; bst.inorder(root); break; case 2: cout<<"2.Deletion"; cout<<"Delete Element ?"; cin>>x; bst.del(x,root); bst.inorder(root); break; case 3: cout<<"3.Nodecopy"; bst.copy(root,root1); cout<<"The new tree is :"; bst.inorder(root1); break; case 4: cout<<"4.Find"; cout<<"Search Element ?"; cin>>x; bst.find(x,root); cout<<" The ancestors are :"; bst.ances(x,root); cout<<" The descendants are :"; bst.desc(x,root); break; case 5: cout<<"5.Findmax"; if (root == NULL) cout<<"Tree is empty"; else { max=bst.findmax(root); cout<<"Largest element is : "<<max->ele<<endl;

82

ADVANCED DATA STRUCTURES USING C++ Lab. File

} break; case 6: cout<<"6.Findmin"; if (root == NULL) cout<<"Tree is empty"; else { min=bst.findmin(root); cout<<"Smallest element is : "<<min->ele<<endl; } break; case 7: cout<<"7.Preorder"; if (root==NULL) cout<<"Tree is empty"; else { cout<<"Preorder traversal (Non-Recursive) is :"; bst.preordernr(root); cout<<"Preorder traversal (Recursive) is :"; bst.preorder(root); } break; case 8: cout<<"8.Inorder"; if (root==NULL) cout<<"Tree is empty"; else { cout<<"Inorder traversal (Non-Recursive) is :"; bst.inordernr(root); cout<<"Inorder traversal (Recursive) is :"; bst.inorder(root); } break; case 9: cout<<"9.Postorder"; if (root==NULL) cout<<"Tree is empty"; else { cout<<"Postorder traversal (Non-Recursive) is :"; bst.postordernr(root);

83

ADVANCED DATA STRUCTURES USING C++ Lab. File

cout<<"Postorder traversal (Recursive) is :"; bst.postorder(root); } break; case 10: cout<<"10.Finding the left Child "; if (root==NULL) cout<<"Tree is empty"; else { cout<<"Parent of the left child ?"; cin>>leftele; bst.leftchild(leftele,root); } break; case 11: cout<<"11.Finding the Right Child "; if (root==NULL) cout<<"Tree is empty"; else { cout<<"Parent of the right child ?"; cin>>rightele; bst.rightchild(rightele,root); } break; case 12: bst.nonodes(root); cout<<"Number of nodes : "<<nodes<<endl; nodes=0; bst.noleaves(root); cout<<"Number of leaves :"<<leaves<<endl; leaves=0; bst.fullnodes(root); cout<<"Number of fullnodes :"<<full<<endl; full=0; cout<<"All leaf nodes are :"; bst.allleaves(root); break; } cout<<"Continue (y/n) ?"; cin>>c; }while (c=='y' || c == 'Y'); return 0; }

84

ADVANCED DATA STRUCTURES USING C++ Lab. File

85

ADVANCED DATA STRUCTURES USING C++ Lab. File

86

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to implement AVL Tree 1. Insertion 2. Deletion 3. Balancing Height # include <iostream.h> # include <stdlib.h> # include <conio.h> struct node { int element; node *left; node *right; int height; }; typedef struct node *nodeptr; class bstree { public: void insert(int,nodeptr &); void del(int, nodeptr &); int deletemin(nodeptr &); void find(int,nodeptr &); nodeptr findmin(nodeptr); nodeptr findmax(nodeptr); void copy(nodeptr &,nodeptr &); void makeempty(nodeptr &); nodeptr nodecopy(nodeptr &); void preorder(nodeptr); void inorder(nodeptr); void postorder(nodeptr); int bsheight(nodeptr); nodeptr srl(nodeptr &); nodeptr drl(nodeptr &); nodeptr srr(nodeptr &); nodeptr drr(nodeptr &); int max(int,int); int nonodes(nodeptr); }; // Inserting a node void bstree::insert(int x,nodeptr &p)

87

ADVANCED DATA STRUCTURES USING C++ Lab. File

{ if (p == NULL) { p = new node; p->element = x; p->left=NULL; p->right = NULL; p->height=0; if (p==NULL) cout<<"Out of Space"; } else { if (x<p->element) { insert(x,p->left); if ((bsheight(p->left) - bsheight(p->right))==2) { if (x < p->left->element) p=srl(p); else p = drl(p); } } else if (x>p->element) { insert(x,p->right); if ((bsheight(p->right) - bsheight(p->left))==2) { if (x > p->right->element) p=srr(p); else p = drr(p); } } else cout<<"Element Exists"; } int m,n,d; m=bsheight(p->left); n=bsheight(p->right); d=max(m,n); p->height = d + 1; } // Finding the Smallest nodeptr bstree::findmin(nodeptr p)

88

ADVANCED DATA STRUCTURES USING C++ Lab. File

{ if (p==NULL) { cout<<"Empty Tree"; return p; } else { while(p->left !=NULL) p=p->left; return p; } } // Finding the Largest nodeptr bstree::findmax(nodeptr p) { if (p==NULL) { cout<<"Empty Tree"; return p; } else { while(p->right !=NULL) p=p->right; return p; } } // Finding an element void bstree::find(int x,nodeptr &p) { if (p==NULL) cout<<"Element not found"; else if (x < p->element) find(x,p->left); else if (x>p->element) find(x,p->right); else cout<<"Element found !"; } // Copy a tree void bstree::copy(nodeptr &p,nodeptr &p1)

89

ADVANCED DATA STRUCTURES USING C++ Lab. File

{ makeempty(p1); p1 = nodecopy(p); } // Make a tree empty void bstree::makeempty(nodeptr &p) { nodeptr d; if (p != NULL) { makeempty(p->left); makeempty(p->right); d=p; free(d); p=NULL; } } // Copy the nodes nodeptr bstree::nodecopy(nodeptr &p) { nodeptr temp; if (p==NULL) return p; else { temp = new node; temp->element = p->element; temp->left = nodecopy(p->left); temp->right = nodecopy(p->right); return temp; } } // Deleting a node void bstree::del(int x,nodeptr &p) { nodeptr d; if (p==NULL) cout<<"Element not found "; else if ( x < p->element) del(x,p->left); else if (x > p->element) del(x,p->right); else if ((p->left == NULL) && (p->right == NULL)) { d=p;

90

ADVANCED DATA STRUCTURES USING C++ Lab. File

free(d); p=NULL; cout<<" Element deleted !"; } else if (p->left == NULL) { d=p; free(d); p=p->right; cout<<" Element deleted !"; } else if (p->right == NULL) { d=p; p=p->left; free(d); cout<<" Element deleted !"; } else p->element = deletemin(p->right); } int bstree::deletemin(nodeptr &p) { int c; cout<<"inside deltemin "; if (p->left == NULL) { c=p->element; p=p->right; return c; } else { c=deletemin(p->left); return c; } } void bstree::preorder(nodeptr p) { if (p!=NULL) { cout<<p->element<<"-->"; preorder(p->left); preorder(p->right); } }

91

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Inorder Printing void bstree::inorder(nodeptr p) { if (p!=NULL) { inorder(p->left); cout<<p->element<<"-->"; inorder(p->right); } } // PostOrder Printing void bstree::postorder(nodeptr p) { if (p!=NULL) { postorder(p->left); postorder(p->right); cout<<p->element<<"-->"; } } int bstree::max(int value1, int value2) { return ((value1 > value2) ? value1 : value2); } int bstree::bsheight(nodeptr p) { int t; if (p == NULL) return -1; else { t = p->height; return t; } } nodeptr bstree:: srl(nodeptr &p1) { nodeptr p2; p2 = p1->left; p1->left = p2->right; p2->right = p1; p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1; p2->height = max(bsheight(p2->left),p1->height) + 1;

92

ADVANCED DATA STRUCTURES USING C++ Lab. File

return p2; } nodeptr bstree:: srr(nodeptr &p1) { nodeptr p2; p2 = p1->right; p1->right = p2->left; p2->left = p1; p1->height = max(bsheight(p1->left),bsheight(p1->right)) + 1; p2->height = max(p1->height,bsheight(p2->right)) + 1; return p2; } nodeptr bstree:: drl(nodeptr &p1) { p1->left=srr(p1->left); return srl(p1); } nodeptr bstree::drr(nodeptr &p1) { p1->right = srl(p1->right); return srr(p1); } int bstree::nonodes(nodeptr p) { int count=0; if (p!=NULL) { nonodes(p->left); nonodes(p->right); count++; } return count; }

int main() { clrscr(); nodeptr root,root1,min,max;//,flag; int a,choice,findele,delele,leftele,rightele,flag; char ch='y';

93

ADVANCED DATA STRUCTURES USING C++ Lab. File

bstree bst; //system("clear"); root = NULL; root1=NULL; cout<<" AVL Tree"; cout<<" ========"; do { cout<<" 1.Insertion 2.FindMin"; cout<<"3.FindMax 4.Find 5.Copy "; cout<<"6.Delete 7.Preorder 8.Inorder"; cout<<"9.Postorder 10.height"; cout<<"Enter the choice:"; cin>>choice; switch(choice) { case 1: cout<<"New node's value ?"; cin>>a; bst.insert(a,root); break; case 2: if (root !=NULL) { min=bst.findmin(root); cout<<" Min element : "<<min->element; } break; case 3: if (root !=NULL) { max=bst.findmax(root); cout<<"max element : "<<max->element; } break; case 4: cout<<"Search node : "; cin>>findele; if (root != NULL) bst.find(findele,root);

94

ADVANCED DATA STRUCTURES USING C++ Lab. File

break; case 5: bst.copy(root,root1); bst.inorder(root1); break; case 6: cout<<"Delete Node ?"; cin>>delele; bst.del(delele,root); bst.inorder(root); break; case 7: cout<<" Preorder Printing... :"; bst.preorder(root); break; case 8: cout<<" Inorder Printing.... :"; bst.inorder(root); break; case 9: cout<<" Postorder Printing... :"; bst.postorder(root); break; case 10: cout<<" Height and Depth is "; cout<<bst.bsheight(root); cout<<"No. of nodes:- "<<bst.nonodes(root); break;

} cout<<" Do u want to continue (y/n) ?"; cin>>ch; }while(ch=='y'); return 0; }

95

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ To Implement a Binary tree // 1. Create a tree 2. Mirror image of Tree 3. Finding height of Tree. #include<iostream.h> #include<conio.h> #include<stdlib.h> //header for standard library function exit(); typedef class bin_tree { public: int data,status; class bin_tree *lchild,*rchild; bin_tree():data(0),lchild(NULL),rchild(NULL),status(0){} class bin_tree* createbt(class bin_tree*,int data); function void leafnodes(class bin_tree*); void display(class bin_tree*);

//pointers to class bin_tree //constructor //create

96

ADVANCED DATA STRUCTURES USING C++ Lab. File

class bin_tree* mirrorimage(class bin_tree*,class bin_tree*); void levelprint(class bin_tree*,int&); }nodebt; simplicity typedef class queue { public: nodebt *data; class queue *next; queue():data(NULL),next(NULL){} nodebt* deletefront(queue **front,queue **rear); queue *insertrear(queue **front,queue **rear,nodebt *data); }que; void nodebt::levelprint(class bin_tree* r,int &height) { que q1; nodebt *check=NULL,*pt=r; que *front=NULL,*rear=NULL; q1.insertrear(&front,&rear,r); q1.insertrear(&front,&rear,check); while(front!=NULL)//q not empty { while(pt!=NULL) { pt=q1.deletefront(&front,&rear); if(pt==NULL) { cout<<endl; height++; q1.insertrear(&front,&rear,check); pt=q1.deletefront(&front,&rear); } if(front==NULL) return; cout<<pt->data<<" "; if(pt->lchild!=NULL) q1.insertrear(&front,&rear,pt->lchild); if(pt->rchild!=NULL) q1.insertrear(&front,&rear,pt->rchild); } } } nodebt* que::deletefront(que **front,que **rear) { nodebt *temp=NULL; if(*front==NULL) { cout<<" //typedef for

97

ADVANCED DATA STRUCTURES USING C++ Lab. File

queue is empty"; } else { temp=(*front)->data; (*front)=(*front)->next; if((*front)==NULL) { *rear=NULL; } } return temp; } que *que::insertrear(que **front,que **rear,nodebt *data) { que *temp=NULL; temp=new queue; temp->data=data; temp->next=NULL; if(*front==NULL) { *front=temp; *rear=temp; } else { (*rear)->next=temp; *rear=(*rear)->next; } return *front; } nodebt* nodebt::mirrorimage(class bin_tree *r,class bin_tree* m) { nodebt *ret=NULL; if(r==NULL) return r; if(r->status==2) { nodebt *temp=new nodebt; temp->data=r->data; temp->status=2; m=temp; ret=temp; } if(r->status==0) { nodebt *temp=new nodebt; temp->data=r->data; temp->status=1;

98

ADVANCED DATA STRUCTURES USING C++ Lab. File

m->rchild=temp; m=m->rchild; } if(r->status==1) { nodebt *temp=new nodebt; temp->data=r->data; temp->status=0; m->lchild=temp; m=m->lchild; } mirrorimage(r->lchild,m); mirrorimage(r->rchild,m); return ret; } void nodebt::leafnodes(class bin_tree* r) { if(r==NULL) return; if(r->lchild==NULL && r->lchild==NULL) cout<<r->data<<" "; leafnodes(r->lchild); leafnodes(r->rchild); } void nodebt::display(class bin_tree* r) { if(r==NULL) return; cout<<" "<<r->data<<" "; display(r->lchild); display(r->rchild); } nodebt* nodebt::createbt(nodebt *r,int data) { int ch=0; if(r==NULL) { nodebt *temp=new nodebt; temp->data=data; temp->status=2; r=temp; } else { cout<<" 1.INSERT AT LEFT OF"<<" "<<r->data; cout<<"

99

ADVANCED DATA STRUCTURES USING C++ Lab. File

2.INSERT AT RIGHT OF"<<" "<<r->data; cout<<" ENTER YOUR CHOICE="; cin>>ch; switch(ch) { case 1:if(r->lchild==NULL) { nodebt *temp=new nodebt; temp->data=data; temp->status=0; r->lchild=temp; } else createbt(r->lchild,data); break; case 2:if(r->rchild==NULL) { nodebt *temp=new nodebt; temp->data=data; temp->status=1; r->rchild=temp; } else createbt(r->rchild,data); break; } } return r; } int main() { int ch=0,data=0,height=0; nodebt *head=NULL,*m=NULL; nodebt t2; do { clrscr(); cout<<"MENU"; cout<<"1.CREATE OR INSERT BINARY TREE"; cout<<"2.PRINT LEAF NODES"; cout<<"3.FIND MIRROR IMAGE OF THE TREE"; cout<<"4.PRINT ORIGINAL AND MIRROR IMAGE LEVELWISE"; cout<<"5.HEIGHT OF TREE"; cout<<"6.EXIT"; cout<<"ENTER YOUR CHOICE="; cin>>ch; switch(ch) { case 1: nodebt t1;

100

ADVANCED DATA STRUCTURES USING C++ Lab. File

do { cout<<"ENTER THE DATA=";cin>>data; head=t1.createbt(head,data); cout<<" DO U WANT TO ADD MORE NODES(1.YES/2.NO)"; cout<<" ENTER YOUR CHOICE"; cin>>ch; } while(ch!=2); t1.display(head); break; case 2: t1.leafnodes(head); break; case 3: m=t2.mirrorimage(head,m); cout<<"MIRRORIMAGE TREE LEVELWISE"; height=0; t2.levelprint(m,height); break; case 4: cout<<"ORIGINAL TREE LEVELWISE"; t1.levelprint(head,height); m=t2.mirrorimage(head,m); cout<<"MIRRORIMAGE TREE LEVELWISE"; height=0; t2.levelprint(m,height); cout<<"HEIGHT OF BINARY TREE="<<height-1; break; case 5:cout<<"HEIGHT OF BINARY TREE="<<height-1; break; case 6:exit(1); } getch(); }while(ch!=6); return 1; }

101

ADVANCED DATA STRUCTURES USING C++ Lab. File

GRAPHS

102

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a Program in C++ To represent graph using adjacency list //

#include<iostream> #include<conio.h> using namespace std; class node // each node of adjacency list { int data; node *next; public : node() //initialize each node { data = 0; next = NULL ; } inline int getdata() // to get data of node { return data; } inline void putdata(int d) //insert data in node { data =d ; } inline node* retNextLink() //return next link of node { return next; } inline void setNext(node* n) // set next link { next = n; } }; class Graph //create a graph adjacency list { int nodes; node **nodearray ; public:

103

ADVANCED DATA STRUCTURES USING C++ Lab. File

Graph(int n) { nodes = n; nodearray = new node*[nodes]; for(int i=0;i<nodes;i++) { nodearray[i] = NULL; } } void displayList() { for(int i=0;i<nodes;i++) { cout << endl; cout << "Node : " << i<< " "; node *temp; temp = nodearray[i]; while(temp != NULL) { cout << temp->getdata(); temp = temp->retNextLink(); cout << " -> "; } cout << " X"; } } void enterData(int index,int nodes) { cout << "Enter Data"; int d; cin >> d; if((d > nodes-1)||(d<0)) { cout << "node do not exist /n"; return; } if(nodearray[index] == NULL) { node *temp = new node; nodearray[index] = temp; temp->setNext(NULL); temp->putdata(d);

104

ADVANCED DATA STRUCTURES USING C++ Lab. File

} else { node *temp1 = nodearray[index] ; node *previous = temp1; while(temp1 != NULL) { previous = temp1; temp1 = temp1->retNextLink(); } node *temp = new node; previous->setNext(temp); temp->setNext(NULL); temp->putdata(d); } } }; int main() { int nodes; cout << "Enter number of elements" ; cin >> nodes; // enter number of nodes Graph g(nodes); int num; int choice; while(1) // create adjacency list { cout << "Enter node no. of which adjacency list to create : "; cin >> num; if( (num > nodes-1) || (num<0) ) { cout << "node do not exist \n"; continue; } g.enterData(num,nodes); cout << "To continue enter 1"; cin >> choice; if(choice != 1) { break; }

105

ADVANCED DATA STRUCTURES USING C++ Lab. File

} g.displayList(); getch(); }

106

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a Program in C++ To represent graph using adjacency matrix //

#include<iostream> #include<conio.h> using namespace std; class Graph { int **array; int nodes; public: Graph(int n) { nodes = n; array = new int*[nodes]; for(int i=0;i<nodes;i++) { array[i] = new int[nodes]; } for(int i=0;i<n;i++) { for(int j=0;j<n;j++) { array[i][j] = 0; } } } void insert(); void display(); }; void Graph :: insert() { cout << endl <<"Enter node whose adjacent u wish to add"; int n; cin >> n; if(n >= nodes) cout << "node does not exist";

107

ADVANCED DATA STRUCTURES USING C++ Lab. File

int data; if(n >= nodes) cout << "node does not exist"; cout << endl << "Enter data"; cin>> data; array[n][data] = 1; } void Graph :: display() { cout << " " ; for(int i=0;i<nodes;i++) cout << "\t"<< i; for(int i=0;i<nodes;i++) { cout << endl; cout << i ; for(int j=0;j<nodes;j++) { cout << "\t"<< array[i][j]; } } } int main() { cout << "Enter Number of nodes"; int nodes; cin >> nodes; Graph g(nodes); int choice; while(1) { g.insert(); cout << "To continue enter 1"; cin >> choice; if(choice != 1) break; } g.display(); getch(); }

108

ADVANCED DATA STRUCTURES USING C++ Lab. File

109

ADVANCED DATA STRUCTURES USING C++ Lab. File

// Write a program in C++ to find the BFS and DFS of a Graph. //

#include<stdio.h> #include<conio.h> #define size 20 int a[10][10],vertex[10],n,e; /*STACK FUNCTIONS*/ #define bottom -1 int stack[size],top=bottom; int stackempty() { return(top=bottom) ? 1:0; } int stackfull() { return(top==size-1) ? 1:0; } void push(int item) { if(stackfull()) printf("7 STACK IS FULL"); else stack[++top]=item; } int pop() { if(stackempty()) { Cout<<" STACK IS EMPTY"; return -1; } else return stack[top--]; } int peep() {

110

ADVANCED DATA STRUCTURES USING C++ Lab. File

if(stackempty()) { Cout<<" STACK IS EMPTY"; return -1; } else return stack[top]; } /* QUEUE FUNCTIONS */ #define start -1 int q[size]; int f=start,r=start; int qempty(){ return(f==r)?1:0; } int qfull(){ return(r==size-1)?1:0;} void addq(int c) { if(qfull()) cout<<QUEUE IS FULL"; else q[++r]=c; } int delq() { if(qempty()) { Cout<<QUEUE IS EMPTY"; return -1; } else return q[++f]; } // j is unvisited adjecent vertex to i int adjvertex(int i) { int j; for(j=0;j<n;j++) if(a[i][j]==1&&vertex[j]==0) return j; return n; } int visitall() {

111

ADVANCED DATA STRUCTURES USING C++ Lab. File

int i; for(i=0;i<n;i++) if(vertex[i]==0) return 0; return 1; } /*FUNCTION FOR BFS*/ void bfs() { int i,j,k,cur=0;//current vertex is startting vertex for(i=0;i<n;i++) vertex[i]=0;//not visited cout<<BFS path => V "<<cur+1; addq(cur); vertex[cur]=1;//marking visited vertex while(!visitall()) { if(qempty()) { Cout<<GRAPH IS DISCONNECTED"; break; } cur=delq(); //visit all verices which are adjecent to current vertex for(j=0;j<n;j++) { //adjecent are not visited if(a[cur][j]==1&&vertex[j]==0) { printf("V%d ",j+1); addq(j); //marking visited vertex vertex[j]=1; } } } } /*FUNCTION FOR DFS*/ void dfs() { int i,j,k,cur=0;//current vertex is startting vertex for(i=0;i<n;i++) vertex[i]=0;//not visited cout<<"DFS path => V%d "<<cur+1; push(cur); vertex[cur]=1;//marking visited vertex while(!visitall())

112

ADVANCED DATA STRUCTURES USING C++ Lab. File

{ do { cur=adjvertex(peep()); if(cur==n) pop(); } while(cur==n&&!stackempty()); if(stackempty()) { Cout<<GRAPH IS DISCONNECTED"; break; } if(cur!=n) { Cout<<" V%<<cur+1; push(cur); vertex[cur]=1;//marking visited vertex } } } /*MAIN PROGRAM*/ void main() { int i,j,k; clrscr(); for(i=0;i<10;i++) for(j=0;j<10;j++) a[i][j]=0; cout<<"ENTER NO OF VERTICES & EDGES OF UNDIRECTED GRAPH : "; cin>>n>>e; cout<<" ENTER EDGES AS PAIR OF VERTICES"; for(k=1;k<=e;k++) { Cout<<"EDGE =>"<<k; Cin>>i>>j; //for undirected graph a[i-1][j-1]=1; } dfs(); bfs(); getch(); }

113

ADVANCED DATA STRUCTURES USING C++ Lab. File

114

ADVANCED DATA STRUCTURES USING C++ Lab. File

Das könnte Ihnen auch gefallen