├── README.md ├── pattern ├── pattern1 ├── numberPattern.cpp ├── NumberPattern2.cpp ├── nopattern1.cpp ├── pattern3.cpp ├── pattern.cpp ├── pattern1.cpp ├── hollowtriangle.cpp ├── NumberDiamond.cpp ├── starpatterndia.cpp ├── patternstar.cpp └── hollow.cpp ├── strreverse.cpp ├── insertionsort.cpp ├── insert ├── vectdiff.txt ├── selection.cpp ├── ASP.TXT ├── bubble.cpp ├── anagram.cpp ├── stack.cpp ├── graph.cpp ├── graphcre.cpp ├── graphadj.cpp ├── Strassens ├── nquee.txt ├── quick sort ├── quicksort.cpp ├── Logest subsequence.txt ├── BSearch ├── SHORT.TXT ├── subsetSumCPP.cpp ├── circularlink.cpp ├── vectorelement.cpp ├── stack using array ├── merge sort ├── deletdoubly.cpp ├── set.cpp ├── mergeoverlaping.cpp ├── merge.cpp ├── fractional_knapsack.cpp ├── bfs.cpp ├── deletion2.cpp ├── vector2.cpp ├── link1.cpp ├── map.cpp ├── vector.cpp ├── deletion1.cpp ├── vectormodi.cpp ├── floydwar.cpp ├── cycledetection.cpp ├── knapsackDP.cpp ├── prim.cpp ├── bellman.cpp ├── avl.cpp ├── insertion.cpp ├── kruskal.c ├── huffman.cpp ├── davl.cpp └── redblack.cpp /README.md: -------------------------------------------------------------------------------- 1 | # DAA 2 | Design and Analysis of Algorithm 3 | -------------------------------------------------------------------------------- /pattern/pattern1: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/komalswami/Data-structures-and-Algorithms/HEAD/pattern/pattern1 -------------------------------------------------------------------------------- /strreverse.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int reverse(int n) 4 | { 5 | int rev=0,rem=0,no; 6 | int n=no; 7 | while(no!=0) 8 | { 9 | rem=no%100; 10 | rem*10 11 | } 12 | } -------------------------------------------------------------------------------- /pattern/numberPattern.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int row; 6 | cin>>row; 7 | for(int i=1;i<=row;i++) 8 | { 9 | for(int j=1;j<=i;j++) 10 | { 11 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int row=5; 6 | for(int i=1;i<=row;i++) 7 | { 8 | for(int sp=i;sp<=row-1;sp++) 9 | { 10 | cout<<" "; 11 | } 12 | for(int j=1;j<=(2*i-1);j++) 13 | { 14 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int row=5; 6 | for(int i=1;i<=row;i++) 7 | { 8 | for(int sp=i;sp<=row-1;sp++) 9 | { 10 | cout<<" "; 11 | } 12 | for(int j=1;j<=(2*i-1);j++) 13 | { 14 | cout< 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int rows=5; 7 | for(int i=1;i<=5;i++) 8 | { 9 | 10 | for(int j=1;j=i;k--) 19 | { 20 | cout<<"*"; 21 | } 22 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int arr[10]={8,6,7,4,3}; 6 | int n=5; 7 | 8 | for(int i=1;i=0 && temp 2 | using namespace std; 3 | void printOccurrences(string txt, string pat) 4 | { 5 | int found = txt.find(pat); 6 | while (found != string::npos) { 7 | cout << "Pattern found at index " << found << endl; 8 | found = txt.find(pat, found + 1); 9 | } 10 | } 11 | 12 | int main() 13 | { 14 | string txt,pat; 15 | getline(cin,txt); 16 | cin>>pat; 17 | printOccurrences(txt, pat); 18 | return 0; 19 | } 20 | -------------------------------------------------------------------------------- /pattern/pattern1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | int main() 4 | { 5 | int rows=5; 6 | // cin>>rows; 7 | for(int i=1;i<=rows;i++) 8 | { 9 | for(int sp=0;sp 2 | #include 3 | void main() 4 | { 5 | int a[20],i,j,k,n; 6 | clrscr(); 7 | printf("Enter array size"); 8 | scanf("%d",&n); 9 | printf("Enter %d integers",n); 10 | for(i=0;i=0 && k 2 | using namespace std; 3 | int main() 4 | { 5 | int rows=5; 6 | for(int i=1;i<=rows;i++) 7 | { 8 | for(int space=i;space<=(rows-1);space++) 9 | { 10 | cout<<" "; 11 | } 12 | for(int j=1;j<=(2*i-1);j++) 13 | { 14 | if(j==1 ||j==(2*i-1)){ 15 | cout<<"*"; 16 | } 17 | else 18 | { 19 | cout<<" "; 20 | } 21 | 22 | } 23 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int row=5; 6 | for(int i=1;i<=row;i++) 7 | { 8 | for(int sp=i;sp<=row-1;sp++) 9 | { 10 | cout<<" "; 11 | } 12 | for(int j=1;j<=(2*i-1);j++) 13 | { 14 | cout<=0;i--) 21 | { 22 | for(int sp=i;sp<=row-1;sp++) 23 | { 24 | cout<<" "; 25 | } 26 | for(int j=1;j<=(2*i-1);j++) 27 | { 28 | cout< 2 | using namespace std; 3 | int main() 4 | { 5 | int arr[20]={4,3,2,1,6}; 6 | int n=5; 7 | int j,temp; 8 | for(int i=0;iarr[j]) 14 | { 15 | temp=arr[min]; 16 | arr[min]=arr[j]; 17 | arr[j]=temp; 18 | } 19 | } 20 | /*if(min!=i) 21 | { 22 | int temp=min; 23 | min=arr[j]; 24 | arr[j]=temp; 25 | }*/ 26 | } 27 | for(int k=0;k 2 | using namespace std; 3 | int main() 4 | { 5 | int row=5; 6 | for(int i=1;i<=row;i++) 7 | { 8 | for(int sp=i;sp<=row-1;sp++) 9 | { 10 | cout<<" "; 11 | } 12 | for(int j=1;j<=(2*i-1);j++) 13 | { 14 | cout<<"*"; 15 | } 16 | cout<=0;i--) 21 | { 22 | for(int sp=i;sp<=row-1;sp++) 23 | { 24 | cout<<" "; 25 | } 26 | for(int j=1;j<=(2*i-1);j++) 27 | { 28 | cout<<"*"; 29 | } 30 | 31 | cout< 2 | #include 3 | int a[20]; 4 | void ASP(int s[],int f[],int k,int n) 5 | { 6 | int m; 7 | m=k+1; 8 | while(m<=n && s[m] 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int arr[10]={8,6,7,4,3}; 7 | int n=5; 8 | 9 | //bubble sort 10 | for(int i=0;iarr[j]) 15 | { 16 | int temp=arr[i]; 17 | arr[i]=arr[j]; 18 | arr[j]=temp; 19 | } 20 | } 21 | cout<<"\n**********************************pass********************************"< 2 | using namespace std; 3 | 4 | bool ana(string str1,string str2) 5 | { 6 | int n1=str1.length(); 7 | int n2=str2.length(); 8 | 9 | if(n1!=n2) 10 | { 11 | return false; 12 | } 13 | 14 | sort(str1.begin(),str1.end()); 15 | sort(str2.begin(),str2.end()); 16 | 17 | for(int i=0;i>str1>>str2; 35 | if(ana(str1,str2)) 36 | { 37 | cout<<"true"; 38 | } 39 | else 40 | { 41 | cout<<"false"; 42 | } 43 | 44 | } -------------------------------------------------------------------------------- /stack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | ***********algo******** 3 | 1. Push the given elements to the stack container one by one. 4 | 2. Keep popping the elements of stack until it becomes empty, and increment the counter variable. 5 | 3. Print the counter variable. 6 | */ 7 | 8 | // CPP program to illustrate 9 | // Application of push() and pop() function 10 | #include 11 | #include 12 | using namespace std; 13 | 14 | int main() 15 | { 16 | int c = 0; 17 | // Empty stack 18 | stack mystack; 19 | mystack.push(5); 20 | mystack.push(13); 21 | mystack.push(0); 22 | mystack.push(9); 23 | mystack.push(4); 24 | // stack becomes 5, 13, 0, 9, 4 25 | 26 | // Counting number of elements in queue 27 | while (!mystack.empty()) { 28 | mystack.pop(); 29 | c++; 30 | } 31 | cout<< c; 32 | } 33 | -------------------------------------------------------------------------------- /pattern/patternstar.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int rows=5; 7 | for(int i=1;i<=5;i++) 8 | { 9 | for(int sp=i;sp<=rows-1;sp++) 10 | { 11 | cout<<" "; 12 | } 13 | for(int j=1;j<=(2*i-1);j++) 14 | { 15 | if(j%2==0) 16 | { 17 | cout<<"*"; 18 | } 19 | else 20 | { 21 | cout<<" "; 22 | } 23 | } 24 | cout<=1;i--) 28 | { 29 | 30 | for(int k=1;k<=space;k++) 31 | { 32 | cout<<" "; 33 | } 34 | for(int j=1;j<=(2*i-1);j++) 35 | { 36 | if(j%2==0){ 37 | cout<<"*"; 38 | } 39 | else 40 | { 41 | cout<<" "; 42 | } 43 | } 44 | space++; 45 | cout< 3 | using namespace std; 4 | 5 | // A utility function to add an edge in an 6 | // undirected graph. 7 | void addEdge(vector adj[], int u, int v) 8 | { 9 | adj[u].push_back(v); 10 | adj[v].push_back(u); 11 | } 12 | 13 | // A utility function to print the adjacency list 14 | // representation of graph 15 | void printGraph(vector adj[], int V) 16 | { 17 | for (int v = 0; v < V; ++v) 18 | { 19 | cout << "\n Adjacency list of vertex " 20 | << v << "\n head "; 21 | for (auto x : adj[v]) 22 | cout << "-> " << x; 23 | printf("\n"); 24 | } 25 | } 26 | 27 | // Driver code 28 | int main() 29 | { 30 | int V = 5; 31 | vector adj[V]; 32 | addEdge(adj, 0, 1); 33 | addEdge(adj, 0, 4); 34 | addEdge(adj, 1, 2); 35 | addEdge(adj, 1, 3); 36 | addEdge(adj, 1, 4); 37 | addEdge(adj, 2, 3); 38 | addEdge(adj, 3, 4); 39 | printGraph(adj, V); 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /pattern/hollow.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | int main() 5 | { 6 | int rows=5; 7 | for(int i=1;i<=5;i++) 8 | { 9 | for(int sp=i;sp<=rows-1;sp++) 10 | { 11 | cout<<" "; 12 | } 13 | for(int j=1;j<=(2*i-1);j++) 14 | { 15 | if(j==1 || j==(2*i-1)) 16 | { 17 | cout<<"*"; 18 | } 19 | else 20 | { 21 | cout<<" "; 22 | } 23 | } 24 | cout<=1;i--) 28 | { 29 | 30 | for(int k=1;k<=space;k++) 31 | { 32 | cout<<" "; 33 | } 34 | for(int j=1;j<=(2*i-1);j++) 35 | { 36 | if(j==1 || j==(2*i-1)) 37 | { 38 | cout<<"*"; 39 | } 40 | else 41 | { 42 | cout<<" "; 43 | } 44 | 45 | } 46 | space++; 47 | cout< 2 | #include 3 | using namespace std; 4 | /*int main() 5 | { 6 | vector g1[5]; 7 | int u=9,v=7; 8 | 9 | for(int i=0;i<5;i++) 10 | { 11 | g1[i].push_back(u); 12 | g1[i].push_back(v); 13 | } 14 | 15 | for(int i=0;i<5;i++){ 16 | for(auto it=g1[i].begin();it!=g1[i].end();it++) 17 | { 18 | cout<<*it<<" "; 19 | } 20 | } 21 | }*/ 22 | 23 | void addEdge(vector adj[],int u,int v) 24 | { 25 | adj[u].push_back(u); 26 | adj[v].push_back(v); 27 | } 28 | void printGraph(vector adj[],int V) 29 | { 30 | for(int i=0;i"< adj[V]; 42 | addEdge(adj,0,1); 43 | addEdge(adj, 0, 4); 44 | addEdge(adj, 1, 2); 45 | addEdge(adj, 1, 3); 46 | addEdge(adj, 1, 4); 47 | addEdge(adj, 2, 3); 48 | addEdge(adj, 3, 4); 49 | printGraph(adj, V); 50 | return 0; 51 | } -------------------------------------------------------------------------------- /graphadj.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | /*int main() 5 | { 6 | vector g1[5]; 7 | int u=9,v=7; 8 | 9 | for(int i=0;i<5;i++) 10 | { 11 | g1[i].push_back(u); 12 | g1[i].push_back(v); 13 | } 14 | 15 | for(int i=0;i<5;i++){ 16 | for(auto it=g1[i].begin();it!=g1[i].end();it++) 17 | { 18 | cout<<*it<<" "; 19 | } 20 | } 21 | }*/ 22 | 23 | void addEdge(vector adj[],int u,int v) 24 | { 25 | adj[u].push_back(u); 26 | adj[v].push_back(v); 27 | } 28 | void printGraph(vector adj[],int V) 29 | { 30 | for(int i=0;i"< adj[V]; 42 | addEdge(adj,0,1); 43 | addEdge(adj, 0, 4); 44 | addEdge(adj, 1, 2); 45 | addEdge(adj, 1, 3); 46 | addEdge(adj, 1, 4); 47 | addEdge(adj, 2, 3); 48 | addEdge(adj, 3, 4); 49 | printGraph(adj, V); 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /Strassens: -------------------------------------------------------------------------------- 1 | //Matrix Multiplication using Strassen's Algorithm 2 | #include 3 | #include 4 | void st(int, int, int, int, int, int, int, int); 5 | int a[2][2], b[2][2], c[2][2]; 6 | void main() 7 | { 8 | int i, j; 9 | clrscr(); 10 | printf("\n Enter matrix A (2x2) :"); 11 | for(i=0;i<2;i++) 12 | for(j=0;j<2;j++) 13 | scanf("%d", &a[i][j]); 14 | printf("\n Enter matrix B (2x2) :"); 15 | for(i=0;i<2;i++) 16 | for(j=0;j<2;j++) 17 | scanf("%d", &b[i][j]); 18 | st(a[0][0],a[0][1],a[1][0],a[1][1],b[0][0],b[0][1],b[1][0],b[1][1]); 19 | printf("\n Matrix C:\n"); 20 | for(i=0;i<2;i++) 21 | { 22 | for(j=0;j<2;j++) 23 | printf("\t%d",c[i][j]); 24 | printf("\n"); 25 | } 26 | getch(); 27 | } 28 | 29 | void st(int a11, int a12, int a21, int a22,int b11, int b12, int b21, int b22) { 30 | int p, q, r, s, t, u, v; 31 | p= (a11 + a22) * ( b11 + b22); 32 | q= (a21 +a22) * b11; 33 | r= a11 * (b12 - b22); 34 | s= a22 * (b21 - b11); 35 | t= (a11 + a12) * b22; 36 | u= (a21 - a11) * ( b11 + b12); 37 | v= (a12 - a22) * ( b21 + b22); 38 | 39 | c[0][0] = p + s - t + v; 40 | c[0][1] = r + t; 41 | c[1][0] = q + s; 42 | c[1][1] = p + r - q + u; 43 | } 44 | -------------------------------------------------------------------------------- /nquee.txt: -------------------------------------------------------------------------------- 1 | /** n-Queens Problem using Backtracking **/ 2 | #include 3 | #include 4 | #include 5 | int a[30],count=0; 6 | int place(int pos) 7 | { 8 | int i; 9 | for(i=1;i 2 | #include 3 | #include 4 | int *a, n; 5 | void quicksort(int p, int q); 6 | int partition(int m, int p); 7 | void main() 8 | { 9 | int i; 10 | clrscr(); 11 | printf(" Enter array size: "); 12 | scanf("%d",&n); 13 | a= (int *) malloc (n); 14 | printf("\n Enter %d integers. : ",n); 15 | for(i=1;i<=n;i++) 16 | scanf("%d",&a[i]); 17 | printf("\n"); 18 | printf("\n quicksort(%d,%d)",1,n); 19 | quicksort(1,n); 20 | printf("\n Sorted List : "); 21 | for(i=1;i<=n;i++) 22 | printf("%3d ",a[i]); 23 | getch(); 24 | } 25 | void quicksort(int p, int q) 26 | { 27 | int j; 28 | if(p a[i]); 54 | do 55 | { 56 | j--; 57 | } while(v < a[j]); 58 | 59 | if(i 2 | 3 | using namespace std; 4 | 5 | void quick_sort(int[],int,int); 6 | int partition(int[],int,int); 7 | 8 | int main() 9 | { 10 | int a[50],n,i; 11 | cout<<"How many elements?"; 12 | cin>>n; 13 | cout<<"\nEnter array elements:"; 14 | 15 | for(i=0;i>a[i]; 17 | 18 | quick_sort(a,0,n-1); 19 | cout<<"\nArray after sorting:"; 20 | 21 | for(i=0;i 3 | #include 4 | int i,j,m,n,c[20][20],cnt=0; 5 | char x[20],y[20],b[20][20]; 6 | void print(int i,int j) 7 | { 8 | if(i==0 || j==0) 9 | return; 10 | if(b[i][j]=='c') 11 | { 12 | print(i-1,j-1); 13 | printf(" %c",x[i-1]); 14 | cnt++; 15 | } 16 | else if(b[i][j]=='l') 17 | print(i,j-1); 18 | else 19 | print(i-1,j); 20 | } 21 | 22 | void lcs() 23 | { 24 | m=strlen(x); 25 | n=strlen(y); 26 | for(i=0;i<=m;i++) 27 | c[i][0]=0; 28 | for(i=0;i<=n;i++) 29 | c[0][i]=0; 30 | //c, u and l denotes cross, upward and left directions respectively 31 | for(i=1;i<=m;i++) 32 | { 33 | for(j=1;j<=n;j++) 34 | { 35 | if(x[i-1]==y[j-1]) 36 | { 37 | c[i][j]=c[i-1][j-1]+1; 38 | 39 | 40 | b[i][j]='c'; 41 | } 42 | else if(c[i][j-1]>=c[i-1][j]) 43 | { 44 | c[i][j]=c[i][j-1]; 45 | b[i][j]='l'; 46 | } 47 | else 48 | { 49 | c[i][j]=c[i-1][j]; 50 | b[i][j]='u'; 51 | } 52 | printf(" %d",c[i][j]); 53 | } 54 | printf("\n"); 55 | } 56 | } 57 | 58 | int main() 59 | { 60 | printf(" Enter 1st sequence:"); 61 | scanf("%s",x); 62 | printf(" Enter 2nd sequence:"); 63 | scanf("%s",y); 64 | printf("\n"); 65 | lcs(); 66 | printf("\n The Longest Common Subsequence is: "); print(m,n); 67 | printf("\n Length of the longest subsequence: %d",cnt); return 0; 68 | } -------------------------------------------------------------------------------- /BSearch: -------------------------------------------------------------------------------- 1 | // Binary Search using recursion: 2 | #include 3 | #include 4 | #include 5 | int *a,cnt=0; 6 | int binsrch(int low, int high, int x); 7 | void main() 8 | { 9 | int i,n,num,pos; 10 | char ans; 11 | clrscr(); 12 | printf(" Enter size of an array: "); 13 | scanf("%d",&n); 14 | a = (int *) malloc(n); 15 | printf("\n Enter %d integers in ascending order:",n); 16 | for(i=1;i<=n;i++) 17 | scanf("%d", &a[i]); 18 | do 19 | { 20 | printf("\n Enter integer to be searched : "); 21 | scanf("%d",&num); 22 | printf("\n low high mid a[mid]"); 23 | pos=binsrch(1,n,num); 24 | if(pos==0) 25 | printf(" \n\n %d not found .",num); 26 | else 27 | printf(" \n\n %d Found at %d",num,pos); 28 | printf(" \n\n Number of comparisions: %d", cnt); 29 | cnt=0; 30 | printf("\n Do u want to cnt...."); 31 | flushall(); 32 | ans = getche(); 33 | } while(ans=='y'); 34 | } 35 | 36 | int binsrch(int low, int high, int x) 37 | { 38 | int mid; 39 | if(low<=high) 40 | { 41 | mid = (low+high)/2; 42 | cnt++; 43 | if(a[mid]==x) 44 | { 45 | printf("\n%5d %5d %5d %5d",low,high,mid,a[mid]); 46 | return (mid); 47 | } 48 | else 49 | if(a[mid] 3 | #include 4 | #define inf 9999 5 | int arr[5][5]; 6 | int cost[5][5]; 7 | int n; 8 | void path() 9 | { 10 | int i,j,k,q,r; 11 | for(k=0;karr[i][k]+arr[k][j]) 23 | arr[i][j]==arr[i][k]+arr[k][j]; 24 | } 25 | } 26 | } 27 | } 28 | printf("\nShortest path : \n"); 29 | for(q=0;q 3 | using namespace std; 4 | 5 | // Taking the matrix as globally 6 | int tab[2000][2000]; 7 | 8 | // Check if possible subset with 9 | // given sum is possible or not 10 | int subsetSum(int a[], int n, int sum) 11 | { 12 | 13 | // If the sum is zero it means 14 | // we got our expected sum 15 | if (sum == 0) 16 | return 1; 17 | 18 | if (n <= 0) 19 | return 0; 20 | 21 | // If the value is not -1 it means it 22 | // already call the function 23 | // with the same value. 24 | // it will save our from the repetation. 25 | if (tab[n - 1][sum] != -1) 26 | return tab[n - 1][sum]; 27 | 28 | // if the value of a[n-1] is 29 | // greater than the sum. 30 | // we call for the next value 31 | if (a[n - 1] > sum) 32 | return tab[n - 1][sum] = subsetSum(a, n - 1, sum); 33 | else 34 | { 35 | 36 | // Here we do two calls because we 37 | // don't know which value is 38 | // full-fill our critaria 39 | // that's why we doing two calls 40 | return tab[n - 1][sum] = subsetSum(a, n - 1, sum) || 41 | subsetSum(a, n - 1, sum - a[n - 1]); 42 | } 43 | } 44 | 45 | // Driver Code 46 | int main() 47 | { 48 | // Storing the value -1 to the matrix 49 | memset(tab, -1, sizeof(tab)); 50 | int n = 5; 51 | int a[] = {1, 5, 3, 7, 4}; 52 | int sum = 12; 53 | 54 | if (subsetSum(a, n, sum)) 55 | { 56 | cout << "YES" << endl; 57 | } 58 | else 59 | cout << "NO" << endl; 60 | 61 | } 62 | -------------------------------------------------------------------------------- /circularlink.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to implement 2 | // the above approach 3 | #include 4 | using namespace std; 5 | 6 | /* structure for a node */ 7 | class Node 8 | { 9 | public: 10 | int data; 11 | Node *next; 12 | }; 13 | 14 | /* Function to insert a node at the beginning 15 | of a Circular linked list */ 16 | void push(Node **head_ref, int data) 17 | { 18 | Node *ptr1 = new Node(); 19 | Node *temp = *head_ref; 20 | ptr1->data = data; 21 | ptr1->next = *head_ref; 22 | 23 | /* If linked list is not NULL then 24 | set the next of last node */ 25 | if (*head_ref != NULL) 26 | { 27 | while (temp->next != *head_ref) 28 | temp = temp->next; 29 | temp->next = ptr1; 30 | } 31 | else 32 | ptr1->next = ptr1; /*For the first node */ 33 | 34 | *head_ref = ptr1; 35 | } 36 | 37 | /* Function to print nodes in 38 | a given Circular linked list */ 39 | void printList(Node *head) 40 | { 41 | Node *temp = head; 42 | if (head != NULL) 43 | { 44 | do 45 | { 46 | cout << temp->data << " "; 47 | temp = temp->next; 48 | } 49 | while (temp != head); 50 | } 51 | } 52 | 53 | /* Driver program to test above functions */ 54 | int main() 55 | { 56 | /* Initialize lists as empty */ 57 | Node *head = NULL; 58 | 59 | /* Created linked list will be 11->2->56->12 */ 60 | push(&head, 12); 61 | push(&head, 56); 62 | push(&head, 2); 63 | push(&head, 11); 64 | 65 | cout << "Contents of Circular Linked List\n "; 66 | printList(head); 67 | 68 | return 0; 69 | } 70 | 71 | -------------------------------------------------------------------------------- /vectorelement.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Modifiers: 3 | 4 | assign() – It assigns new value to the vector elements by replacing old ones 5 | push_back() – It push the elements into a vector from the back 6 | pop_back() – It is used to pop or remove elements from a vector from the back. 7 | insert() – It inserts new elements before the element at the specified position 8 | erase() – It is used to remove elements from a container from the specified position or range. 9 | swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ. 10 | clear() – It is used to remove all the elements of the vector container 11 | emplace() – It extends the container by inserting new element at position 12 | emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector 13 | 14 | */ 15 | 16 | // C++ program to illustrate the 17 | // element accesser in vector 18 | #include 19 | using namespace std; 20 | 21 | int main() 22 | { 23 | vector g1; 24 | 25 | for (int i = 1; i <= 10; i++) 26 | g1.push_back(i * 10); 27 | 28 | cout << "\nReference operator [g] : g1[2] = " << g1[2]; 29 | 30 | cout << "\nat : g1.at(4) = " << g1.at(4); 31 | 32 | cout << "\nfront() : g1.front() = " << g1.front(); 33 | 34 | cout << "\nback() : g1.back() = " << g1.back(); 35 | 36 | // pointer to the first element 37 | int* pos = g1.data(); 38 | 39 | cout << "\nThe first element is " << *pos; 40 | return 0; 41 | } 42 | -------------------------------------------------------------------------------- /stack using array: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | # include 4 | # define MAX 5 //Define Stack Size 5 | struct stack // Stack Structure 6 | { 7 | int a[MAX]; 8 | int TOP; 9 | }s; 10 | void push(); 11 | void pop(); 12 | void display(); 13 | void main() 14 | { 15 | char ch; 16 | int choice; 17 | clrscr(); 18 | s.TOP=-1; //Stack Initialization 19 | do 20 | { 21 | printf("\n1. Push 2. Pop 3. Display 4. Exit"); 22 | printf("\nEnter your choice : "); 23 | scanf("%d",&choice); 24 | switch(choice) 25 | { 26 | case 1: push(); break; 27 | case 2: pop(); break; 28 | case 3: display(); break; 29 | case 4: exit(0); 30 | default: printf("\n Wrong Choice..."); 31 | } 32 | printf("\nDo u want to cnt..."); 33 | flushall(); 34 | ch=getche(); 35 | } while(ch == 'y'); 36 | } 37 | void push() //Insertion of data items 38 | { 39 | char ch; 40 | int x; 41 | do 42 | { 43 | if(s.TOP == MAX-1) // Test Stack overflow 44 | { 45 | printf("\n Stack Overflow "); 46 | break; 47 | } 48 | else // If Stack Not Full 49 | { 50 | printf("\n Enter data item : "); 51 | scanf("%d",&x); 52 | s.TOP++; 53 | s.a[s.TOP] = x; 54 | } 55 | printf("\nDo U want to push more? (y/n) "); 56 | flushall(); 57 | ch=getche(); 58 | } while(ch == 'y'); 59 | } 60 | void pop() //Deletion of Data Items 61 | { 62 | char ch; 63 | do 64 | { 65 | if(s.TOP == -1) //Test Stack Underflow 66 | { 67 | printf("\n Stack Underflow "); 68 | break; 69 | } 70 | else // If stack Not empty 71 | { 72 | printf("\n %d has been deleted", s.a[s.TOP]); 73 | s.TOP--; 74 | } 75 | printf("\n Do U want to pop more? (y/n) "); 76 | flushall(); 77 | ch=getche(); 78 | } while(ch == 'y'); 79 | } 80 | void display() //Display Stack Data Items 81 | { 82 | int i; 83 | if(s.TOP == -1) //Stack empty 84 | printf("\n Stack Empty" ); 85 | else 86 | { 87 | for(i=s.TOP ; i>=0 ; i--) 88 | printf("\n %d: %3d",i,s.a[i]); 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /merge sort: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | #include 5 | int a[20],b[20]; 6 | int n; 7 | void mergsort(int low, int high); 8 | void merge(int low, int mid, int high); 9 | void main() 10 | { 11 | int i; 12 | clock_t start, end; 13 | clrscr(); 14 | printf(" Enter size of an array: "); 15 | scanf("%d",&n); 16 | printf("\n Enter %d integers. : ",n); 17 | for(i=0;imid) // Left list get terminated 72 | for(k=j;k<=high;k++) 73 | { 74 | b[i]=a[k]; //Append elements from right list to sorted list 75 | i++; 76 | } 77 | else // Right list get terminated 78 | for(k=h;k<=mid;k++) 79 | { 80 | b[i]=a[k]; // Append elements from left list to sorted list 81 | i++; 82 | } 83 | printf("\n"); 84 | for(k=low;k<=high;k++) // Display passes 85 | { 86 | a[k]=b[k]; 87 | printf("%5d ",a[k]); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /deletdoubly.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | class node 5 | { 6 | public: 7 | int data; 8 | node* next; 9 | node* prev; 10 | }; 11 | void push(node** head_ref,int data) 12 | { 13 | node* new_node=new node(); 14 | new_node->data=data; 15 | 16 | new_node->next=*head_ref; 17 | new_node->prev=NULL; 18 | 19 | if(*head_ref!=NULL) 20 | { 21 | new_node->prev=new_node; 22 | } 23 | *head_ref=new_node; 24 | } 25 | /* 26 | void push(node** head_ref,int new_data) 27 | { 28 | node *new_node=new node(); 29 | new_node->data=new_data; 30 | new_node->next=*head_ref; 31 | new_node->prev=NULL; 32 | //if 1 2 is list and push 3 then 3 1 2 so 33 | if(*head_ref !=NULL) 34 | new_node->prev=new_node; 35 | 36 | *head_ref=new_node; 37 | } 38 | */ 39 | 40 | void delet(node** head_ref,node* del) 41 | { 42 | //base case 43 | if(*head_ref==NULL || del==NULL) 44 | { 45 | return; 46 | } 47 | //first node 48 | if(*head_ref==del) 49 | { 50 | *head_ref=del->next; 51 | } 52 | 53 | if(del->prev!=NULL) 54 | { 55 | del->next->prev=del->prev; 56 | 57 | } 58 | if(del->next!=NULL) 59 | { 60 | del->prev->next=del->next; 61 | } 62 | free(del); 63 | return; 64 | } 65 | 66 | 67 | 68 | 69 | 70 | void printlist(node* head_ref) 71 | { 72 | while(head_ref!=NULL) 73 | { 74 | // cout<prev<<" "<data<<" "<next<data; 76 | head_ref=head_ref->next; 77 | } 78 | cout<next); 94 | printlist(head); 95 | return 0; 96 | } 97 | -------------------------------------------------------------------------------- /set.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | // empty set container 10 | set > s1; 11 | 12 | // insert elements in random order 13 | s1.insert(40); 14 | s1.insert(30); 15 | s1.insert(60); 16 | s1.insert(20); 17 | s1.insert(50); 18 | 19 | // only one 50 will be added to the set 20 | s1.insert(50); 21 | s1.insert(10); 22 | 23 | // printing set s1 24 | set >::iterator itr; 25 | cout << "\nThe set s1 is : \n"; 26 | for (itr = s1.begin(); 27 | itr != s1.end(); ++itr) 28 | { 29 | cout << *itr << ","; 30 | } 31 | cout << endl; 32 | 33 | // assigning the elements from s1 to s2 34 | set s2(s1.begin(), s1.end()); 35 | 36 | // print all elements of the set s2 37 | cout << "\nThe set s2 after assign from s1 is : \n"; 38 | for (itr = s2.begin(); 39 | itr != s2.end(); ++itr) 40 | { 41 | cout << *itr << ","; 42 | } 43 | cout << endl; 44 | 45 | // remove all elements up to 30 in s2 46 | cout 47 | << "\ns2 after removal of elements less than 30 :\n"; 48 | s2.erase(s2.begin(), s2.find(30)); 49 | for (itr = s2.begin(); 50 | itr != s2.end(); ++itr) { 51 | cout <<*itr<<","; 52 | } 53 | 54 | // remove element with value 50 in s2 55 | int num; 56 | num = s2.erase(50); 57 | cout << "\ns2.erase(50) : "; 58 | cout << num << " removed\n"; 59 | for (itr = s2.begin(); 60 | itr != s2.end(); ++itr) 61 | { 62 | cout <<*itr<<","; 63 | } 64 | 65 | cout << endl; 66 | 67 | // lower bound and upper bound for set s1 68 | cout << "s1.lower_bound(40) : \n" 69 | << *s1.lower_bound(40) 70 | << endl; 71 | cout << "s1.upper_bound(40) : \n" 72 | << *s1.upper_bound(40) 73 | << endl; 74 | 75 | // lower bound and upper bound for set s2 76 | cout << "s2.lower_bound(40) :\n" 77 | << *s2.lower_bound(40) 78 | << endl; 79 | cout << "s2.upper_bound(40) : \n" 80 | << *s2.upper_bound(40) 81 | << endl; 82 | 83 | return 0; 84 | } 85 | -------------------------------------------------------------------------------- /mergeoverlaping.cpp: -------------------------------------------------------------------------------- 1 | // A C++ program for merging overlapping intervals 2 | #include 3 | using namespace std; 4 | 5 | // An interval has start time and end time 6 | struct Interval 7 | { 8 | int start, end; 9 | }; 10 | 11 | // Compares two intervals according to their staring time. 12 | // This is needed for sorting the intervals using library 13 | // function std::sort(). See http://goo.gl/iGspV 14 | bool compareInterval(Interval i1, Interval i2) 15 | { 16 | return (i1.start < i2.start); 17 | } 18 | 19 | // The main function that takes a set of intervals, merges 20 | // overlapping intervals and prints the result 21 | void mergeIntervals(Interval arr[], int n) 22 | { 23 | // Test if the given set has at least one interval 24 | if (n <= 0) 25 | return; 26 | 27 | // Create an empty stack of intervals 28 | stack s; 29 | 30 | // sort the intervals in increasing order of start time 31 | sort(arr, arr+n, compareInterval); 32 | 33 | // push the first interval to stack 34 | s.push(arr[0]); 35 | 36 | // Start from the next interval and merge if necessary 37 | for (int i = 1 ; i < n; i++) 38 | { 39 | // get interval from stack top 40 | Interval top = s.top(); 41 | 42 | // if current interval is not overlapping with stack top, 43 | // push it to the stack 44 | if (top.end < arr[i].start) 45 | s.push(arr[i]); 46 | 47 | // Otherwise update the ending time of top if ending of current 48 | // interval is more 49 | else if (top.end < arr[i].end) 50 | { 51 | top.end = arr[i].end; 52 | s.pop(); 53 | s.push(top); 54 | } 55 | } 56 | 57 | // Print contents of stack 58 | cout << "\n The Merged Intervals are: "; 59 | while (!s.empty()) 60 | { 61 | Interval t = s.top(); 62 | cout << "[" << t.start << "," << t.end << "] "; 63 | s.pop(); 64 | } 65 | return; 66 | } 67 | int main() 68 | { 69 | Interval arr[] = { {6,8}, {1,9}, {2,4}, {4,7} }; 70 | int n = sizeof(arr)/sizeof(arr[0]); 71 | mergeIntervals(arr, n); 72 | return 0; 73 | } 74 | -------------------------------------------------------------------------------- /merge.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Merge Sort 2 | #include 3 | using namespace std; 4 | 5 | // Merges two subarrays of arr[]. 6 | // First subarray is arr[l..m] 7 | // Second subarray is arr[m+1..r] 8 | void merge(int arr[], int l, int m, int r) 9 | { 10 | int n1 = m - l + 1; 11 | int n2 = r - m; 12 | 13 | // Create temp arrays 14 | int L[n1], R[n2]; 15 | 16 | // Copy data to temp arrays L[] and R[] 17 | for (int i = 0; i < n1; i++) 18 | L[i] = arr[l + i]; 19 | for (int j = 0; j < n2; j++) 20 | R[j] = arr[m + 1 + j]; 21 | 22 | // Merge the temp arrays back into arr[l..r] 23 | 24 | // Initial index of first subarray 25 | int i = 0; 26 | 27 | // Initial index of second subarray 28 | int j = 0; 29 | 30 | // Initial index of merged subarray 31 | int k = l; 32 | 33 | while (i < n1 && j < n2) { 34 | if (L[i] <= R[j]) { 35 | arr[k] = L[i]; 36 | i++; 37 | } 38 | else { 39 | arr[k] = R[j]; 40 | j++; 41 | } 42 | k++; 43 | } 44 | 45 | // Copy the remaining elements of 46 | // L[], if there are any 47 | while (i < n1) { 48 | arr[k] = L[i]; 49 | i++; 50 | k++; 51 | } 52 | 53 | // Copy the remaining elements of 54 | // R[], if there are any 55 | while (j < n2) { 56 | arr[k] = R[j]; 57 | j++; 58 | k++; 59 | } 60 | } 61 | 62 | // l is for left index and r is 63 | // right index of the sub-array 64 | // of arr to be sorted */ 65 | void mergeSort(int arr[],int l,int r){ 66 | if(l>=r){ 67 | return;//returns recursively 68 | } 69 | int m = (l+r-1)/2; 70 | mergeSort(arr,l,m); 71 | mergeSort(arr,m+1,r); 72 | merge(arr,l,m,r); 73 | } 74 | 75 | // UTILITY FUNCTIONS 76 | // Function to print an array 77 | void printArray(int A[], int size) 78 | { 79 | for (int i = 0; i < size; i++) 80 | cout << A[i] << " "; 81 | } 82 | 83 | // Driver code 84 | int main() 85 | { 86 | int arr[] = { 12, 11, 13, 5, 6, 7 }; 87 | int arr_size = sizeof(arr) / sizeof(arr[0]); 88 | 89 | cout << "Given array is \n"; 90 | printArray(arr, arr_size); 91 | 92 | mergeSort(arr, 0, arr_size - 1); 93 | 94 | cout << "\nSorted array is \n"; 95 | printArray(arr, arr_size); 96 | return 0; 97 | } 98 | 99 | -------------------------------------------------------------------------------- /fractional_knapsack.cpp: -------------------------------------------------------------------------------- 1 | // C/C++ program to solve fractional Knapsack Problem 2 | #include 3 | 4 | using namespace std; 5 | 6 | // Structure for an item which stores weight and 7 | // corresponding value of Item 8 | struct Item { 9 | int value, weight; 10 | 11 | // Constructor 12 | Item(int value, int weight) 13 | { 14 | this->value=value; 15 | this->weight=weight; 16 | } 17 | }; 18 | 19 | // Comparison function to sort Item according to val/weight 20 | // ratio 21 | bool cmp(struct Item a, struct Item b) 22 | { 23 | double r1 = (double)a.value / (double)a.weight; 24 | double r2 = (double)b.value / (double)b.weight; 25 | return r1 > r2; 26 | } 27 | 28 | // Main greedy function to solve problem 29 | double fractionalKnapsack(int W, struct Item arr[], int n) 30 | { 31 | // sorting Item on basis of ratio 32 | sort(arr, arr + n, cmp); 33 | 34 | // Uncomment to see new order of Items with their 35 | // ratio 36 | /* 37 | for (int i = 0; i < n; i++) 38 | { 39 | cout << arr[i].value << " " << arr[i].weight << " : 40 | " 41 | << ((double)arr[i].value / arr[i].weight) << 42 | endl; 43 | } 44 | */ 45 | 46 | int curWeight = 0; // Current weight in knapsack 47 | double finalvalue = 0.0; // Result (value in Knapsack) 48 | 49 | // Looping through all Items 50 | for (int i = 0; i < n; i++) { 51 | // If adding Item won't overflow, add it completely 52 | if (curWeight + arr[i].weight <= W) { 53 | curWeight += arr[i].weight; 54 | finalvalue += arr[i].value; 55 | } 56 | 57 | // If we can't add current Item, add fractional part 58 | // of it 59 | else { 60 | int remain = W - curWeight; 61 | finalvalue += arr[i].value 62 | * ((double)remain 63 | / (double)arr[i].weight); 64 | break; 65 | } 66 | } 67 | 68 | // Returning final value 69 | return finalvalue; 70 | } 71 | 72 | // Driver code 73 | int main() 74 | { 75 | int W = 50; // Weight of knapsack 76 | Item arr[] = { { 60, 10 }, { 100, 20 }, { 120, 30 } }; 77 | 78 | int n = sizeof(arr) / sizeof(arr[0]); 79 | 80 | // Function call 81 | cout << "Maximum value we can obtain = " 82 | << fractionalKnapsack(W, arr, n); 83 | return 0; 84 | } 85 | //greedy -------------------------------------------------------------------------------- /bfs.cpp: -------------------------------------------------------------------------------- 1 | // Program to print BFS traversal from a given 2 | // source vertex. BFS(int s) traverses vertices 3 | // reachable from s. 4 | #include 5 | #include 6 | 7 | using namespace std; 8 | 9 | // This class represents a directed graph using 10 | // adjacency list representation 11 | class Graph 12 | { 13 | int V; // No. of vertices 14 | 15 | // Pointer to an array containing adjacency 16 | // lists 17 | list *adj; 18 | public: 19 | Graph(int V); // Constructor 20 | 21 | // function to add an edge to graph 22 | void addEdge(int v, int w); 23 | 24 | // prints BFS traversal from a given source s 25 | void BFS(int s); 26 | }; 27 | 28 | Graph::Graph(int V) 29 | { 30 | this->V = V; 31 | adj = new list[V]; 32 | } 33 | 34 | void Graph::addEdge(int v, int w) 35 | { 36 | adj[v].push_back(w); // Add w to v’s list. 37 | } 38 | 39 | void Graph::BFS(int s) 40 | { 41 | // Mark all the vertices as not visited 42 | bool *visited = new bool[V]; 43 | for(int i = 0; i < V; i++) 44 | visited[i] = false; 45 | 46 | // Create a queue for BFS 47 | list queue; 48 | 49 | // Mark the current node as visited and enqueue it 50 | visited[s] = true; 51 | queue.push_back(s); 52 | 53 | // 'i' will be used to get all adjacent 54 | // vertices of a vertex 55 | list::iterator i; 56 | 57 | while(!queue.empty()) 58 | { 59 | // Dequeue a vertex from queue and print it 60 | s = queue.front(); 61 | cout << s << " "; 62 | queue.pop_front(); 63 | 64 | // Get all adjacent vertices of the dequeued 65 | // vertex s. If a adjacent has not been visited, 66 | // then mark it visited and enqueue it 67 | for (i = adj[s].begin(); i != adj[s].end(); ++i) 68 | { 69 | if (!visited[*i]) 70 | { 71 | visited[*i] = true; 72 | queue.push_back(*i); 73 | } 74 | } 75 | } 76 | } 77 | 78 | // Driver program to test methods of graph class 79 | int main() 80 | { 81 | // Create a graph given in the above diagram 82 | Graph g(4); 83 | g.addEdge(0, 1); 84 | g.addEdge(0, 2); 85 | g.addEdge(1, 2); 86 | g.addEdge(2, 0); 87 | g.addEdge(2, 3); 88 | g.addEdge(3, 3); 89 | 90 | cout << "Following is Breadth First Traversal " 91 | << "(starting from vertex 2) \n"; 92 | g.BFS(2); 93 | 94 | return 0; 95 | } 96 | -------------------------------------------------------------------------------- /deletion2.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | using namespace std; 3 | 4 | // A linked list node 5 | class Node{ 6 | public: 7 | int data; 8 | Node* next; 9 | }; 10 | 11 | // Given a reference (pointer to pointer) 12 | // to the head of a list and an int, 13 | // inserts a new node on the front of the 14 | // list. 15 | void push(Node** head_ref, int new_data) 16 | { 17 | Node* new_node = new Node(); 18 | new_node->data = new_data; 19 | new_node->next = (*head_ref); 20 | (*head_ref) = new_node; 21 | } 22 | void deleteNode(Node** head_ref, int key) 23 | { 24 | 25 | // Store head node 26 | Node* temp = *head_ref; 27 | Node* prev = NULL; 28 | 29 | // If head node itself holds 30 | // the key to be deleted 31 | if (temp != NULL && temp->data == key) 32 | { 33 | *head_ref = temp->next; // Changed head 34 | delete temp; // free old head 35 | return; 36 | } 37 | 38 | // Else Search for the key to be deleted, 39 | // keep track of the previous node as we 40 | // need to change 'prev->next' */ 41 | while (temp != NULL && temp->data != key) 42 | { 43 | prev = temp; 44 | temp = temp->next; 45 | } 46 | 47 | // If key was not present in linked list 48 | if (temp == NULL) 49 | return; 50 | 51 | // Unlink the node from linked list 52 | prev->next = temp->next; 53 | 54 | // Free memory 55 | delete temp; 56 | } 57 | 58 | // This function prints contents of 59 | // linked list starting from the 60 | // given node 61 | void printList(Node* node) 62 | { 63 | while (node != NULL) 64 | { 65 | cout << node->data << " "; 66 | node = node->next; 67 | } 68 | } 69 | 70 | // Driver code 71 | int main() 72 | { 73 | 74 | // Start with the empty list 75 | Node* head = NULL; 76 | 77 | // Add elements in linked list 78 | push(&head, 7); 79 | push(&head, 1); 80 | push(&head, 3); 81 | push(&head, 2); 82 | 83 | puts("Created Linked List: "); 84 | printList(head); 85 | 86 | deleteNode(&head, 1); 87 | puts("\nLinked List after Deletion of 1: "); 88 | 89 | printList(head); 90 | 91 | return 0; 92 | } -------------------------------------------------------------------------------- /vector2.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | 3 | size() – Returns the number of elements in the vector. 4 | max_size() – Returns the maximum number of elements that the vector can hold. 5 | capacity() – Returns the size of the storage space currently allocated to the vector expressed as number of elements. 6 | resize(n) – Resizes the container so that it contains ‘n’ elements. 7 | empty() – Returns whether the container is empty. 8 | shrink_to_fit() – Reduces the capacity of the container to fit its size and destroys all elements beyond the capacity. 9 | reserve() – Requests that the vector capacity be at least enough to contain n elements. 10 | 11 | */ 12 | 13 | // C++ program to illustrate the 14 | // capacity function in vector 15 | #include 16 | #include 17 | 18 | using namespace std; 19 | 20 | int main() 21 | { 22 | vector g1; 23 | 24 | for (int i = 1; i <= 5; i++) 25 | g1.push_back(i); 26 | 27 | cout << "Size : " << g1.size(); 28 | cout << "\nCapacity : " << g1.capacity(); 29 | cout << "\nMax_Size : " << g1.max_size(); 30 | 31 | // resizes the vector size to 4 32 | g1.resize(4); 33 | 34 | // prints the vector size after resize() 35 | cout << "\nSize : " << g1.size(); 36 | 37 | // checks if the vector is empty or not 38 | if (g1.empty() == false) 39 | cout << "\nVector is not empty"; 40 | else 41 | cout << "\nVector is empty"; 42 | 43 | // Shrinks the vector 44 | g1.shrink_to_fit(); 45 | cout << "\nVector elements are: "; 46 | for (auto it = g1.begin(); it != g1.end(); it++) 47 | cout << *it << " "; 48 | 49 | return 0; 50 | } 51 | 52 | /* 53 | All Vector Functions : 54 | 55 | vector::begin() and vector::end() 56 | vector rbegin() and rend() 57 | vector::cbegin() and vector::cend() 58 | vector::crend() and vector::crbegin() 59 | vector::assign() 60 | vector::at() 61 | vector::back() 62 | vector::capacity() 63 | vector::clear() 64 | vector::push_back() 65 | vector::pop_back() 66 | vector::empty() 67 | vector::erase() 68 | 69 | vector::size() 70 | vector::swap() 71 | vector::reserve() 72 | vector::resize() 73 | vector::shrink_to_fit() 74 | vector::operator= 75 | vector::operator[] 76 | vector::front() 77 | vector::data() 78 | vector::emplace_back() 79 | vector::emplace() 80 | vector::max_size() 81 | vector::insert() 82 | 83 | 84 | */ 85 | -------------------------------------------------------------------------------- /link1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | using namespace std; 5 | class node 6 | { 7 | public: 8 | int data; 9 | node* next; 10 | }; 11 | void printList(node* n) 12 | { 13 | while (n!=NULL) 14 | { 15 | cout<data<<" "; 16 | n=n->next; 17 | } 18 | } 19 | void insertAtFirst(node** head_ref,int newdata) 20 | { 21 | //1. allocate node 22 | node* newnode =new node(); 23 | 24 | //2. put in the data 25 | newnode->data=newdata; 26 | 27 | //insert as first 28 | 29 | //3. make next of new node as head 30 | newnode->next=(*head_ref); 31 | 32 | //4. move the head to point to the new node 33 | (*head_ref)=newnode; 34 | } 35 | void insertAfter(node* prev_node,int newdata) 36 | { 37 | if(prev_node==NULL) 38 | { 39 | cout<<"empty"; 40 | return; 41 | } 42 | 43 | node* newnode=new node(); 44 | newnode->data=newdata; 45 | 46 | newnode->next=prev_node->next; 47 | prev_node->next=newnode; 48 | } 49 | void insertAtLast(node** head_ref,int newdata) 50 | { 51 | //1. allocate node 52 | node* newnode=new node(); 53 | 54 | //2.allocate data 55 | newnode->data=newdata; 56 | 57 | newnode->next=NULL; 58 | 59 | node* last=*head_ref; 60 | 61 | while(last!=NULL) 62 | { 63 | last=last->next; 64 | } 65 | 66 | last->next=newnode; 67 | return; 68 | 69 | } 70 | int main() 71 | { 72 | node* head=NULL; 73 | node* second=NULL; 74 | node* third=NULL; 75 | 76 | head=new node(); 77 | second=new node(); 78 | third=new node(); 79 | 80 | head->data=1; 81 | head->next=second; 82 | 83 | second->data=2; 84 | second->next=third; 85 | 86 | third->data=3; 87 | third->next=NULL; 88 | 89 | cout<<"\n************************************************"<next,9); 100 | printList(head); 101 | 102 | 103 | cout<<"\n************************************************"< 2 | #include 3 | #include 4 | 5 | using namespace std; 6 | 7 | int main() 8 | { 9 | 10 | // empty map container 11 | map gquiz1; 12 | 13 | // insert elements in random order 14 | gquiz1.insert(pair(1, 40)); 15 | gquiz1.insert(pair(2, 30)); 16 | gquiz1.insert(pair(3, 60)); 17 | gquiz1.insert(pair(4, 20)); 18 | gquiz1.insert(pair(5, 50)); 19 | gquiz1.insert(pair(6, 50)); 20 | gquiz1.insert(pair(7, 10)); 21 | 22 | // printing map gquiz1 23 | map::iterator itr; 24 | cout << "\nThe map gquiz1 is : \n"; 25 | cout << "\tKEY\tELEMENT\n"; 26 | for (itr = gquiz1.begin(); itr != gquiz1.end(); ++itr) { 27 | cout << '\t' << itr->first 28 | << '\t' << itr->second << '\n'; 29 | } 30 | cout << endl; 31 | 32 | // assigning the elements from gquiz1 to gquiz2 33 | map gquiz2(gquiz1.begin(), gquiz1.end()); 34 | 35 | // print all elements of the map gquiz2 36 | cout << "\nThe map gquiz2 after" 37 | << " assign from gquiz1 is : \n"; 38 | cout << "\tKEY\tELEMENT\n"; 39 | for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 40 | cout << '\t' << itr->first 41 | << '\t' << itr->second << '\n'; 42 | } 43 | cout << endl; 44 | 45 | // remove all elements up to 46 | // element with key=3 in gquiz2 47 | cout << "\ngquiz2 after removal of" 48 | " elements less than key=3 : \n"; 49 | cout << "\tKEY\tELEMENT\n"; 50 | gquiz2.erase(gquiz2.begin(), gquiz2.find(3)); 51 | for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 52 | cout << '\t' << itr->first 53 | << '\t' << itr->second << '\n'; 54 | } 55 | 56 | // remove all elements with key = 4 57 | int num; 58 | num = gquiz2.erase(4); 59 | cout << "\ngquiz2.erase(4) : "; 60 | cout << num << " removed \n"; 61 | cout << "\tKEY\tELEMENT\n"; 62 | for (itr = gquiz2.begin(); itr != gquiz2.end(); ++itr) { 63 | cout << '\t' << itr->first 64 | << '\t' << itr->second << '\n'; 65 | } 66 | 67 | cout << endl; 68 | 69 | // lower bound and upper bound for map gquiz1 key = 5 70 | cout << "gquiz1.lower_bound(5) : " 71 | << "\tKEY = "; 72 | cout << gquiz1.lower_bound(5)->first << '\t'; 73 | cout << "\tELEMENT = " 74 | << gquiz1.lower_bound(5)->second << endl; 75 | cout << "gquiz1.upper_bound(5) : " 76 | << "\tKEY = "; 77 | cout << gquiz1.upper_bound(5)->first << '\t'; 78 | cout << "\tELEMENT = " 79 | << gquiz1.upper_bound(5)->second << endl; 80 | 81 | return 0; 82 | } 83 | -------------------------------------------------------------------------------- /vector.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Vectors are same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators. In vectors, data is inserted at the end. Inserting at the end takes differential time, as sometimes there may be a need of extending the array. Removing the last element takes only constant time because no resizing happens. Inserting and erasing at the beginning or in the middle is linear in time. 3 | 4 | 5 | 6 | Certain functions associated with the vector are: 7 | Iterators 8 | 9 | begin() – Returns an iterator pointing to the first element in the vector 10 | end() – Returns an iterator pointing to the theoretical element that follows the last element in the vector 11 | rbegin() – Returns a reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element 12 | rend() – Returns a reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end) 13 | cbegin() – Returns a constant iterator pointing to the first element in the vector. 14 | cend() – Returns a constant iterator pointing to the theoretical element that follows the last element in the vector. 15 | crbegin() – Returns a constant reverse iterator pointing to the last element in the vector (reverse beginning). It moves from last to first element 16 | crend() – Returns a constant reverse iterator pointing to the theoretical element preceding the first element in the vector (considered as reverse end) 17 | 18 | */ 19 | 20 | // C++ program to illustrate the 21 | // iterators in vector 22 | #include 23 | #include 24 | 25 | using namespace std; 26 | 27 | int main() 28 | { 29 | vector g1; 30 | 31 | for (int i = 1; i <= 5; i++) 32 | g1.push_back(i); 33 | 34 | cout << "Output of begin and end: "; 35 | for (auto i = g1.begin(); i != g1.end(); ++i) 36 | cout << *i << " "; 37 | 38 | cout << "\nOutput of cbegin and cend: "; 39 | for (auto i = g1.cbegin(); i != g1.cend(); ++i) 40 | cout << *i << " "; 41 | 42 | cout << "\nOutput of rbegin and rend: "; 43 | for (auto ir = g1.rbegin(); ir != g1.rend(); ++ir) 44 | cout << *ir << " "; 45 | 46 | cout << "\nOutput of crbegin and crend : "; 47 | for (auto ir = g1.crbegin(); ir != g1.crend(); ++ir) 48 | cout << *ir << " "; 49 | 50 | return 0; 51 | } 52 | -------------------------------------------------------------------------------- /deletion1.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | 4 | // A linked list node 5 | struct Node 6 | { 7 | int data; 8 | struct Node *next; 9 | }; 10 | 11 | /* Given a reference (pointer to pointer) to the head of a list 12 | and an int inserts a new node on the front of the list. */ 13 | void push(struct Node** head_ref, int new_data) 14 | { 15 | struct Node* new_node = (struct Node*) malloc(sizeof(struct Node)); 16 | new_node->data = new_data; 17 | new_node->next = (*head_ref); 18 | (*head_ref) = new_node; 19 | } 20 | 21 | /* Given a reference (pointer to pointer) to the head of a list 22 | and a position, deletes the node at the given position */ 23 | void deleteNode(struct Node **head_ref, int position) 24 | { 25 | // If linked list is empty 26 | if (*head_ref == NULL) 27 | return; 28 | 29 | // Store head node 30 | struct Node* temp = *head_ref; 31 | 32 | // If head needs to be removed 33 | if (position == 0) 34 | { 35 | *head_ref = temp->next; // Change head 36 | free(temp); // free old head 37 | return; 38 | } 39 | 40 | // Find previous node of the node to be deleted 41 | for (int i=0; temp!=NULL && inext; 43 | 44 | // If position is more than number of nodes 45 | if (temp == NULL || temp->next == NULL) 46 | return; 47 | 48 | // Node temp->next is the node to be deleted 49 | // Store pointer to the next of node to be deleted 50 | struct Node *next = temp->next->next; 51 | 52 | // Unlink the node from linked list 53 | free(temp->next); // Free memory 54 | 55 | temp->next = next; // Unlink the deleted node from list 56 | } 57 | 58 | // This function prints contents of linked list starting from 59 | // the given node 60 | void printList(struct Node *node) 61 | { 62 | while (node != NULL) 63 | { 64 | printf(" %d ", node->data); 65 | node = node->next; 66 | } 67 | } 68 | 69 | /* Driver program to test above functions*/ 70 | int main() 71 | { 72 | /* Start with the empty list */ 73 | struct Node* head = NULL; 74 | 75 | push(&head, 7); 76 | push(&head, 1); 77 | push(&head, 3); 78 | push(&head, 2); 79 | push(&head, 8); 80 | 81 | puts("Created Linked List: "); 82 | printList(head); 83 | deleteNode(&head, 4); 84 | puts("\nLinked List after Deletion at position 4: "); 85 | printList(head); 86 | return 0; 87 | } -------------------------------------------------------------------------------- /vectormodi.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | Modifiers: 3 | 4 | assign() – It assigns new value to the vector elements by replacing old ones 5 | push_back() – It push the elements into a vector from the back 6 | pop_back() – It is used to pop or remove elements from a vector from the back. 7 | insert() – It inserts new elements before the element at the specified position 8 | erase() – It is used to remove elements from a container from the specified position or range. 9 | swap() – It is used to swap the contents of one vector with another vector of same type. Sizes may differ. 10 | clear() – It is used to remove all the elements of the vector container 11 | emplace() – It extends the container by inserting new element at position 12 | emplace_back() – It is used to insert a new element into the vector container, the new element is added to the end of the vector 13 | */ 14 | 15 | // C++ program to illustrate the 16 | // Modifiers in vector 17 | #include 18 | #include 19 | using namespace std; 20 | 21 | int main() 22 | { 23 | // Assign vector 24 | vector v; 25 | 26 | // fill the array with 10 five times 27 | v.assign(5, 10); 28 | 29 | cout << "The vector elements are: "; 30 | for (int i = 0; i < v.size(); i++) 31 | cout << v[i] << " "; 32 | 33 | // inserts 15 to the last position 34 | v.push_back(15); 35 | int n = v.size(); 36 | cout << "\nThe last element is: " << v[n - 1]; 37 | 38 | // removes last element 39 | v.pop_back(); 40 | 41 | // prints the vector 42 | cout << "\nThe vector elements are: "; 43 | for (int i = 0; i < v.size(); i++) 44 | cout << v[i] << " "; 45 | 46 | // inserts 5 at the beginning 47 | v.insert(v.begin(), 5); 48 | 49 | cout << "\nThe first element is: " << v[0]; 50 | 51 | // removes the first element 52 | v.erase(v.begin()); 53 | 54 | cout << "\nThe first element is: " << v[0]; 55 | 56 | // inserts at the beginning 57 | v.emplace(v.begin(), 5); 58 | cout << "\nThe first element is: " << v[0]; 59 | 60 | // Inserts 20 at the end 61 | v.emplace_back(20); 62 | n = v.size(); 63 | cout << "\nThe last element is: " << v[n - 1]; 64 | 65 | // erases the vector 66 | v.clear(); 67 | cout << "\nVector size after erase(): " << v.size(); 68 | 69 | // two vector to perform swap 70 | vector v1, v2; 71 | v1.push_back(1); 72 | v1.push_back(2); 73 | v2.push_back(3); 74 | v2.push_back(4); 75 | 76 | cout << "\n\nVector 1: "; 77 | for (int i = 0; i < v1.size(); i++) 78 | cout << v1[i] << " "; 79 | 80 | cout << "\nVector 2: "; 81 | for (int i = 0; i < v2.size(); i++) 82 | cout << v2[i] << " "; 83 | 84 | // Swaps v1 and v2 85 | v1.swap(v2); 86 | 87 | cout << "\nAfter Swap \nVector 1: "; 88 | for (int i = 0; i < v1.size(); i++) 89 | cout << v1[i] << " "; 90 | 91 | cout << "\nVector 2: "; 92 | for (int i = 0; i < v2.size(); i++) 93 | cout << v2[i] << " "; 94 | } 95 | -------------------------------------------------------------------------------- /floydwar.cpp: -------------------------------------------------------------------------------- 1 | //Floyd warshall algorithm 2 | 3 | #include 4 | 5 | using namespace std; 6 | 7 | 8 | 9 | int main() 10 | 11 | { 12 | 13 | int i,j,k; 14 | 15 | int n,e; 16 | 17 | int s,d,w; 18 | 19 | 20 | 21 | cout<<"Enter the number of vertices "; 22 | 23 | cin>>n; 24 | 25 | 26 | 27 | //adjacency matrix 28 | 29 | //initialized to infinity 30 | 31 | vector > distMat(n,vector(n,INT_MAX)); 32 | 33 | 34 | 35 | for(i=0;i>e; 50 | 51 | 52 | 53 | cout<<"Enter the src, dest and weight of each edge"<>s>>d>>w; 60 | 61 | 62 | 63 | //add to the adjacency list 64 | 65 | 66 | 67 | distMat[s-1][d-1]=w; 68 | 69 | } 70 | 71 | 72 | 73 | //now, we have the adjacency matrix 74 | 75 | //we will create n matrices from this considering a vertex as an intermediate vertex 76 | 77 | 78 | 79 | //intermediate 80 | 81 | for(k=0;k 3 | using namespace std; 4 | 5 | /* Link list node */ 6 | struct Node { 7 | int data; 8 | struct Node* next; 9 | }; 10 | 11 | /* Function to remove loop. 12 | Used by detectAndRemoveLoop() */ 13 | void removeLoop(struct Node*, struct Node*); 14 | 15 | /* This function detects and 16 | removes loop in the list 17 | If loop was there in the 18 | list then it returns 1, 19 | otherwise returns 0 */ 20 | int detectAndRemoveLoop(struct Node* list) 21 | { 22 | struct Node *slow_p = list, *fast_p = list; 23 | 24 | while (slow_p && fast_p && fast_p->next) 25 | { 26 | slow_p = slow_p->next; 27 | fast_p = fast_p->next->next; 28 | 29 | /* If slow_p and fast_p meet at 30 | some point then 31 | there is a loop */ 32 | if (slow_p == fast_p) { 33 | removeLoop(slow_p, list); 34 | 35 | /* Return 1 to indicate that loop is found */ 36 | return 1; 37 | } 38 | } 39 | 40 | /* Return 0 to indeciate that ther is no loop*/ 41 | return 0; 42 | } 43 | 44 | /* Function to remove loop. 45 | loop_node --> Pointer to 46 | one of the loop nodes 47 | head --> Pointer to the 48 | start node of the linked list */ 49 | void removeLoop(struct Node* loop_node, struct Node* head) 50 | { 51 | struct Node* ptr1; 52 | struct Node* ptr2; 53 | 54 | /* Set a pointer to the beginning 55 | of the Linked List and 56 | move it one by one to find the 57 | first node which is 58 | part of the Linked List */ 59 | ptr1 = head; 60 | while (1) { 61 | /* Now start a pointer from 62 | loop_node and check if 63 | it ever reaches ptr2 */ 64 | ptr2 = loop_node; 65 | while (ptr2->next != loop_node 66 | && ptr2->next != ptr1) 67 | ptr2 = ptr2->next; 68 | 69 | /* If ptr2 reahced ptr1 70 | then there is a loop. So 71 | break the loop */ 72 | if (ptr2->next == ptr1) 73 | break; 74 | 75 | /* If ptr2 did't reach ptr1 76 | then try the next node 77 | * after ptr1 */ 78 | ptr1 = ptr1->next; 79 | } 80 | 81 | /* After the end of loop ptr2 82 | is the last node of the 83 | loop. So make next of ptr2 as NULL */ 84 | ptr2->next = NULL; 85 | } 86 | 87 | /* Function to print linked list */ 88 | void printList(struct Node* node) 89 | { 90 | while (node != NULL) { 91 | cout << node->data << " "; 92 | node = node->next; 93 | } 94 | } 95 | 96 | struct Node* newNode(int key) 97 | { 98 | struct Node* temp = new Node(); 99 | temp->data = key; 100 | temp->next = NULL; 101 | return temp; 102 | } 103 | 104 | // Driver Code 105 | int main() 106 | { 107 | struct Node* head = newNode(50); 108 | head->next = newNode(20); 109 | head->next->next = newNode(15); 110 | head->next->next->next = newNode(4); 111 | head->next->next->next->next = newNode(10); 112 | 113 | /* Create a loop for testing */ 114 | head->next->next->next->next->next = head->next->next; 115 | 116 | detectAndRemoveLoop(head); 117 | 118 | cout << "Linked List after removing loop" << endl; 119 | 120 | printList(head); 121 | 122 | return 0; 123 | } 124 | -------------------------------------------------------------------------------- /knapsackDP.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | 3 | using namespace std; 4 | 5 | 6 | 7 | int knapsack_dp(int n, int M, int w[], int p[]) 8 | 9 | { 10 | 11 | int i,j; 12 | 13 | 14 | 15 | //create a matrix to memoize the values using dynamic programming 16 | 17 | int knapsack[n+1][M+1]; 18 | 19 | 20 | 21 | //knapsack[i][j] denotes the maximum attainable value of items in knpasack with i available 22 | 23 | //items and capacity of knapsack being j 24 | 25 | 26 | 27 | //initializing knapsack[0][j]=0 for 0<=j<=M 28 | 29 | //because if there is no item, no value can be attained 30 | 31 | for(j=0;j<=M;j++) 32 | 33 | knapsack[0][j]=0; 34 | 35 | 36 | 37 | //initializing knapsack[i][0]=0 for 0<=i<=n, 38 | 39 | //because in a bag of zero capacity, no item can be placed 40 | 41 | for(i=0;i<=n;i++) 42 | 43 | knapsack[i][0]=0; 44 | 45 | 46 | 47 | //now, filling the matrix in bottom up manner 48 | 49 | for(i=1;i<=n;i++) 50 | 51 | { 52 | 53 | for(j=1;j<=M;j++) 54 | 55 | { 56 | 57 | //check if the weight of current item i is less than or equal to the capacity of sack, 58 | 59 | //take maximum of once including the current item and once not including 60 | 61 | if(w[i-1]<=j) 62 | 63 | { 64 | 65 | knapsack[i][j]=max(knapsack[i-1][j],p[i-1]+knapsack[i-1][j-w[i-1]]); 66 | 67 | } 68 | 69 | 70 | 71 | //can not include the current item in this case 72 | 73 | else 74 | 75 | { 76 | 77 | knapsack[i][j]=knapsack[i-1][j]; 78 | 79 | } 80 | 81 | } 82 | 83 | } 84 | 85 | 86 | 87 | 88 | 89 | return knapsack[n][M]; 90 | 91 | 92 | 93 | 94 | 95 | } 96 | 97 | 98 | 99 | int main() 100 | 101 | { 102 | 103 | int i,j; 104 | 105 | int n; //number of items 106 | 107 | int M; //capacity of knapsack 108 | 109 | 110 | 111 | cout<<"Enter the no. of items "; 112 | 113 | cin>>n; 114 | 115 | 116 | 117 | int w[n]; //weight of items 118 | 119 | int p[n]; //value of items 120 | 121 | 122 | 123 | cout<<"Enter the weight and price of all items"<>w[i]>>p[i]; 130 | 131 | } 132 | 133 | 134 | 135 | cout<<"enter the capacity of knapsack "; 136 | 137 | cin>>M; 138 | 139 | 140 | 141 | 142 | 143 | int result=knapsack_dp(n,M,w,p); 144 | 145 | 146 | 147 | //the maximum value will be given by knasack[n][M], ie. using n items with capacity M 148 | 149 | cout<<"The maximum value of items that can be put into knapsack is "< 5 | using namespace std; 6 | 7 | // Number of vertices in the graph 8 | #define V 5 9 | 10 | // A utility function to find the vertex with 11 | // minimum key value, from the set of vertices 12 | // not yet included in MST 13 | int minKey(int key[], bool mstSet[]) 14 | { 15 | // Initialize min value 16 | int min = INT_MAX, min_index; 17 | 18 | for (int v = 0; v < V; v++) 19 | if (mstSet[v] == false && key[v] < min) 20 | min = key[v], min_index = v; 21 | 22 | return min_index; 23 | } 24 | 25 | // A utility function to print the 26 | // constructed MST stored in parent[] 27 | void printMST(int parent[], int graph[V][V]) 28 | { 29 | cout<<"Edge \tWeight\n"; 30 | for (int i = 1; i < V; i++) 31 | cout< 2 | 3 | using namespace std; 4 | 5 | 6 | 7 | //every edge has 3 values associated with it source, destination and weight 8 | 9 | struct edge 10 | 11 | { 12 | 13 | int s,d,w; 14 | 15 | }; 16 | 17 | 18 | 19 | int bellmanFord(int n, int e, int src, vector &edge, vector &dist) 20 | 21 | { 22 | 23 | int i,j; 24 | 25 | int s,d,w; 26 | 27 | 28 | 29 | i=src; 30 | 31 | 32 | 33 | dist[i-1]=0; 34 | 35 | 36 | 37 | //n-1 passes 38 | 39 | for(i=1;i>n; 128 | 129 | 130 | 131 | cout<<"Enter the number of edges "; 132 | 133 | cin>>e; 134 | 135 | 136 | 137 | vector edge(e); 138 | 139 | 140 | 141 | cout<<"Enter the src, dest and weight of each edge"<>s>>d>>edge[i].w; 148 | 149 | edge[i].s=s-1; 150 | 151 | edge[i].d=d-1; 152 | 153 | } 154 | 155 | 156 | 157 | cout<<"Enter the source vertex "; 158 | 159 | cin>>src; 160 | 161 | 162 | 163 | 164 | 165 | //create a vector of size n(for n vertices) and initialize the value of each element to infinity 166 | 167 | //dist[i]=the minimum distance of vertex i from source vertex 168 | 169 | vector dist(n,INT_MAX); 170 | 171 | 172 | 173 | i=bellmanFord(n,e,src,edge,dist); 174 | 175 | 176 | 177 | cout< 2 | using namespace std; 3 | 4 | class node 5 | { 6 | public: 7 | int key; 8 | node *left; 9 | node *right; 10 | int height; 11 | }; 12 | int max(int a,int b); 13 | int height(node *n) 14 | { 15 | if(n==NULL) 16 | return 0; 17 | return n->height; 18 | } 19 | int max(int a,int b) 20 | { 21 | return(a>b)?a:b; 22 | } 23 | node* newNode(int key) 24 | { 25 | node* node = new node(); 26 | node->key = key; 27 | node->left = NULL; 28 | node->right = NULL; 29 | node->height = 1; // new node is initially 30 | // added at leaf 31 | return(node); 32 | } 33 | node *rightRotate(node *y) 34 | { 35 | node *x = y->left; 36 | node *T2 = x->right; 37 | 38 | // Perform rotation 39 | x->right = y; 40 | y->left = T2; 41 | 42 | // Update heights 43 | y->height = max(height(y->left), 44 | height(y->right)) + 1; 45 | x->height = max(height(x->left), 46 | height(x->right)) + 1; 47 | 48 | // Return new root 49 | return x; 50 | } 51 | 52 | node *leftRotate(node *x) 53 | { 54 | node *y = x->right; 55 | node *T2 = y->left; 56 | 57 | // Perform rotation 58 | y->left = x; 59 | x->right = T2; 60 | 61 | // Update heights 62 | x->height = max(height(x->left), 63 | height(x->right)) + 1; 64 | y->height = max(height(y->left), 65 | height(y->right)) + 1; 66 | 67 | // Return new root 68 | return y; 69 | } 70 | 71 | int getBalance(node *N) 72 | { 73 | if (N == NULL) 74 | return 0; 75 | return height(N->left) - height(N->right); 76 | } 77 | 78 | node* insert(node* node, int key) 79 | { 80 | /* 1. Perform the normal BST insertion */ 81 | if (node == NULL) 82 | return(newNode(key)); 83 | 84 | if (key < node->key) 85 | node->left = insert(node->left, key); 86 | else if (key > node->key) 87 | node->right = insert(node->right, key); 88 | else // Equal keys are not allowed in BST 89 | return node; 90 | 91 | /* 2. Update height of this ancestor node */ 92 | node->height = 1 + max(height(node->left), 93 | height(node->right)); 94 | 95 | /* 3. Get the balance factor of this ancestor 96 | node to check whether this node became 97 | unbalanced */ 98 | int balance = getBalance(node); 99 | if (balance > 1 && key < node->left->key) 100 | return rightRotate(node); 101 | 102 | // Right Right Case 103 | if(balance < -1 && key > node->right->key) 104 | { 105 | return leftRotate(node); 106 | } 107 | 108 | // Left Right Case 109 | if(balance > 1 && key > node->left->key) 110 | { 111 | node->left = leftRotate(node->left); 112 | return rightRotate(node); 113 | } 114 | 115 | // Right Left Case 116 | if(balance < -1 && key < node->right->key) 117 | { 118 | node->right = rightRotate(node->right); 119 | return leftRotate(node); 120 | } 121 | 122 | /* return the (unchanged) node pointer */ 123 | return node; 124 | } 125 | void preOrder(node *root) 126 | { 127 | if(root != NULL) 128 | { 129 | cout << root->key << " "; 130 | preOrder(root->left); 131 | preOrder(root->right); 132 | } 133 | } 134 | 135 | int main() 136 | { 137 | node *root = NULL; 138 | 139 | /* Constructing tree given in 140 | the above figure */ 141 | root = insert(root, 10); 142 | root = insert(root, 20); 143 | root = insert(root, 30); 144 | root = insert(root, 40); 145 | root = insert(root, 50); 146 | root = insert(root, 25); 147 | 148 | /* The constructed AVL Tree would be 149 | 30 150 | / \ 151 | 20 40 152 | / \ \ 153 | 10 25 50 154 | */ 155 | cout << "Preorder traversal of the " 156 | "constructed AVL tree is \n"; 157 | preOrder(root); 158 | 159 | return 0; 160 | } -------------------------------------------------------------------------------- /insertion.cpp: -------------------------------------------------------------------------------- 1 | // A complete working C++ program to demonstrate 2 | // all insertion methods on Linked List 3 | #include 4 | using namespace std; 5 | 6 | // A linked list node 7 | class Node 8 | { 9 | public: 10 | int data; 11 | Node *next; 12 | }; 13 | 14 | /* Given a reference (pointer to pointer) 15 | to the head of a list and an int, inserts 16 | a new node on the front of the list. */ 17 | void push(Node** head_ref, int new_data) 18 | { 19 | /* 1. allocate node */ 20 | Node* new_node = new Node(); 21 | 22 | /* 2. put in the data */ 23 | new_node->data = new_data; 24 | 25 | /* 3. Make next of new node as head */ 26 | new_node->next = (*head_ref); 27 | 28 | /* 4. move the head to point to the new node */ 29 | (*head_ref) = new_node; 30 | } 31 | 32 | /* Given a node prev_node, insert a new node after the given 33 | prev_node */ 34 | void insertAfter(Node* prev_node, int new_data) 35 | { 36 | /*1. check if the given prev_node is NULL */ 37 | if (prev_node == NULL) 38 | { 39 | cout<<"the given previous node cannot be NULL"; 40 | return; 41 | } 42 | 43 | /* 2. allocate new node */ 44 | Node* new_node = new Node(); 45 | 46 | /* 3. put in the data */ 47 | new_node->data = new_data; 48 | 49 | /* 4. Make next of new node as next of prev_node */ 50 | new_node->next = prev_node->next; 51 | 52 | /* 5. move the next of prev_node as new_node */ 53 | prev_node->next = new_node; 54 | } 55 | 56 | /* Given a reference (pointer to pointer) to the head 57 | of a list and an int, appends a new node at the end */ 58 | void append(Node** head_ref, int new_data) 59 | { 60 | /* 1. allocate node */ 61 | Node* new_node = new Node(); 62 | 63 | Node *last = *head_ref; /* used in step 5*/ 64 | 65 | /* 2. put in the data */ 66 | new_node->data = new_data; 67 | 68 | /* 3. This new node is going to be 69 | the last node, so make next of 70 | it as NULL*/ 71 | new_node->next = NULL; 72 | 73 | /* 4. If the Linked List is empty, 74 | then make the new node as head */ 75 | if (*head_ref == NULL) 76 | { 77 | *head_ref = new_node; 78 | return; 79 | } 80 | 81 | /* 5. Else traverse till the last node */ 82 | while (last->next != NULL) 83 | last = last->next; 84 | 85 | /* 6. Change the next of last node */ 86 | last->next = new_node; 87 | return; 88 | } 89 | 90 | // This function prints contents of 91 | // linked list starting from head 92 | void printList(Node *node) 93 | { 94 | while (node != NULL) 95 | { 96 | cout<<" "<data; 97 | node = node->next; 98 | } 99 | } 100 | 101 | /* Driver code*/ 102 | int main() 103 | { 104 | /* Start with the empty list */ 105 | Node* head = NULL; 106 | printList(head); 107 | cout<<"\n************************************************"<NULL 110 | append(&head, 6); 111 | printList(head); 112 | cout<<"\n************************************************"<6->NULL 116 | push(&head, 7); 117 | printList(head); 118 | cout<<"\n************************************************"<7->6->NULL 121 | push(&head, 1); 122 | printList(head); 123 | cout<<"\n************************************************"<7->6->4->NULL 126 | append(&head, 4); 127 | printList(head); 128 | cout<<"\n************************************************"<7->8->6->4->NULL 131 | insertAfter(head->next, 8); 132 | printList(head); 133 | cout<<"\n************************************************"< 5 | #include 6 | #include 7 | 8 | // a structure to represent a weighted edge in graph 9 | struct Edge { 10 | int src, dest, weight; 11 | }; 12 | 13 | // a structure to represent a connected, undirected 14 | // and weighted graph 15 | struct Graph { 16 | // V-> Number of vertices, E-> Number of edges 17 | int V, E; 18 | 19 | // graph is represented as an array of edges. 20 | // Since the graph is undirected, the edge 21 | // from src to dest is also edge from dest 22 | // to src. Both are counted as 1 edge here. 23 | struct Edge* edge; 24 | }; 25 | 26 | // Creates a graph with V vertices and E edges 27 | struct Graph* createGraph(int V, int E) 28 | { 29 | struct Graph* graph = (struct Graph*)(malloc(sizeof(struct Graph))); 30 | graph->V = V; 31 | graph->E = E; 32 | 33 | graph->edge = (struct Edge*)malloc(sizeof( struct Edge)); 34 | 35 | return graph; 36 | } 37 | 38 | // A structure to represent a subset for union-find 39 | struct subset { 40 | int parent; 41 | int rank; 42 | }; 43 | 44 | // A utility function to find set of an element i 45 | // (uses path compression technique) 46 | int find(struct subset subsets[], int i) 47 | { 48 | // find root and make root as parent of i 49 | // (path compression) 50 | if (subsets[i].parent != i) 51 | subsets[i].parent 52 | = find(subsets, subsets[i].parent); 53 | 54 | return subsets[i].parent; 55 | } 56 | 57 | // A function that does union of two sets of x and y 58 | // (uses union by rank) 59 | void Union(struct subset subsets[], int x, int y) 60 | { 61 | int xroot = find(subsets, x); 62 | int yroot = find(subsets, y); 63 | 64 | // Attach smaller rank tree under root of high 65 | // rank tree (Union by Rank) 66 | if (subsets[xroot].rank < subsets[yroot].rank) 67 | subsets[xroot].parent = yroot; 68 | else if (subsets[xroot].rank > subsets[yroot].rank) 69 | subsets[yroot].parent = xroot; 70 | 71 | // If ranks are same, then make one as root and 72 | // increment its rank by one 73 | else 74 | { 75 | subsets[yroot].parent = xroot; 76 | subsets[xroot].rank++; 77 | } 78 | } 79 | 80 | // Compare two edges according to their weights. 81 | // Used in qsort() for sorting an array of edges 82 | int myComp(const void* a, const void* b) 83 | { 84 | struct Edge* a1 = (struct Edge*)a; 85 | struct Edge* b1 = (struct Edge*)b; 86 | return a1->weight > b1->weight; 87 | } 88 | 89 | // The main function to construct MST using Kruskal's 90 | // algorithm 91 | void KruskalMST(struct Graph* graph) 92 | { 93 | int V = graph->V; 94 | struct Edge 95 | result[V]; // Tnis will store the resultant MST 96 | int e = 0; // An index variable, used for result[] 97 | int i = 0; // An index variable, used for sorted edges 98 | 99 | // Step 1: Sort all the edges in non-decreasing 100 | // order of their weight. If we are not allowed to 101 | // change the given graph, we can create a copy of 102 | // array of edges 103 | qsort(graph->edge, graph->E, sizeof(graph->edge[0]), 104 | myComp); 105 | 106 | // Allocate memory for creating V ssubsets 107 | struct subset* subsets 108 | = (struct subset*)malloc(V * sizeof(struct subset)); 109 | 110 | // Create V subsets with single elements 111 | for (int v = 0; v < V; ++v) { 112 | subsets[v].parent = v; 113 | subsets[v].rank = 0; 114 | } 115 | 116 | // Number of edges to be taken is equal to V-1 117 | while (e < V - 1 && i < graph->E) { 118 | // Step 2: Pick the smallest edge. And increment 119 | // the index for next iteration 120 | struct Edge next_edge = graph->edge[i++]; 121 | 122 | int x = find(subsets, next_edge.src); 123 | int y = find(subsets, next_edge.dest); 124 | 125 | // If including this edge does't cause cycle, 126 | // include it in result and increment the index 127 | // of result for next edge 128 | if (x != y) { 129 | result[e++] = next_edge; 130 | Union(subsets, x, y); 131 | } 132 | // Else discard the next_edge 133 | } 134 | 135 | // print the contents of result[] to display the 136 | // built MST 137 | printf( 138 | "Following are the edges in the constructed MST\n"); 139 | int minimumCost = 0; 140 | for (i = 0; i < e; ++i) 141 | { 142 | printf("%d -- %d == %d\n", result[i].src, 143 | result[i].dest, result[i].weight); 144 | minimumCost += result[i].weight; 145 | } 146 | printf("Minimum Cost Spanning tree : %d",minimumCost); 147 | return; 148 | } 149 | 150 | // Driver program to test above functions 151 | int main() 152 | { 153 | /* Let us create following weighted graph 154 | 10 155 | 0--------1 156 | | \ | 157 | 6| 5\ |15 158 | | \ | 159 | 2--------3 160 | 4 */ 161 | int V = 4; // Number of vertices in graph 162 | int E = 5; // Number of edges in graph 163 | struct Graph* graph = createGraph(V, E); 164 | 165 | // add edge 0-1 166 | graph->edge[0].src = 0; 167 | graph->edge[0].dest = 1; 168 | graph->edge[0].weight = 10; 169 | 170 | // add edge 0-2 171 | graph->edge[1].src = 0; 172 | graph->edge[1].dest = 2; 173 | graph->edge[1].weight = 6; 174 | 175 | // add edge 0-3 176 | graph->edge[2].src = 0; 177 | graph->edge[2].dest = 3; 178 | graph->edge[2].weight = 5; 179 | 180 | // add edge 1-3 181 | graph->edge[3].src = 1; 182 | graph->edge[3].dest = 3; 183 | graph->edge[3].weight = 15; 184 | 185 | // add edge 2-3 186 | graph->edge[4].src = 2; 187 | graph->edge[4].dest = 3; 188 | graph->edge[4].weight = 4; 189 | 190 | KruskalMST(graph); 191 | 192 | return 0; 193 | } 194 | -------------------------------------------------------------------------------- /huffman.cpp: -------------------------------------------------------------------------------- 1 | // C++ program for Huffman Coding 2 | #include 3 | #include 4 | using namespace std; 5 | 6 | // This constant can be avoided by explicitly 7 | // calculating height of Huffman Tree 8 | #define MAX_TREE_HT 100 9 | 10 | // A Huffman tree node 11 | struct MinHeapNode { 12 | 13 | // One of the input characters 14 | char data; 15 | 16 | // Frequency of the character 17 | unsigned freq; 18 | 19 | // Left and right child of this node 20 | struct MinHeapNode *left, *right; 21 | }; 22 | 23 | // A Min Heap: Collection of 24 | // min-heap (or Huffman tree) nodes 25 | struct MinHeap { 26 | 27 | // Current size of min heap 28 | unsigned size; 29 | 30 | // capacity of min heap 31 | unsigned capacity; 32 | 33 | // Attay of minheap node pointers 34 | struct MinHeapNode** array; 35 | }; 36 | 37 | // A utility function allocate a new 38 | // min heap node with given character 39 | // and frequency of the character 40 | struct MinHeapNode* newNode(char data, unsigned freq) 41 | { 42 | struct MinHeapNode* temp 43 | = (struct MinHeapNode*)malloc 44 | (sizeof(struct MinHeapNode)); 45 | 46 | temp->left = temp->right = NULL; 47 | temp->data = data; 48 | temp->freq = freq; 49 | 50 | return temp; 51 | } 52 | 53 | // A utility function to create 54 | // a min heap of given capacity 55 | struct MinHeap* createMinHeap(unsigned capacity) 56 | 57 | { 58 | 59 | struct MinHeap* minHeap 60 | = (struct MinHeap*)malloc(sizeof(struct MinHeap)); 61 | 62 | // current size is 0 63 | minHeap->size = 0; 64 | 65 | minHeap->capacity = capacity; 66 | 67 | minHeap->array 68 | = (struct MinHeapNode**)malloc(minHeap-> 69 | capacity * sizeof(struct MinHeapNode*)); 70 | return minHeap; 71 | } 72 | 73 | // A utility function to 74 | // swap two min heap nodes 75 | void swapMinHeapNode(struct MinHeapNode** a, 76 | struct MinHeapNode** b) 77 | 78 | { 79 | 80 | struct MinHeapNode* t = *a; 81 | *a = *b; 82 | *b = t; 83 | } 84 | 85 | // The standard minHeapify function. 86 | void minHeapify(struct MinHeap* minHeap, int idx) 87 | 88 | { 89 | 90 | int smallest = idx; 91 | int left = 2 * idx + 1; 92 | int right = 2 * idx + 2; 93 | 94 | if (left < minHeap->size && minHeap->array[left]-> 95 | freq < minHeap->array[smallest]->freq) 96 | smallest = left; 97 | 98 | if (right < minHeap->size && minHeap->array[right]-> 99 | freq < minHeap->array[smallest]->freq) 100 | smallest = right; 101 | 102 | if (smallest != idx) { 103 | swapMinHeapNode(&minHeap->array[smallest], 104 | &minHeap->array[idx]); 105 | minHeapify(minHeap, smallest); 106 | } 107 | } 108 | 109 | // A utility function to check 110 | // if size of heap is 1 or not 111 | int isSizeOne(struct MinHeap* minHeap) 112 | { 113 | 114 | return (minHeap->size == 1); 115 | } 116 | 117 | // A standard function to extract 118 | // minimum value node from heap 119 | struct MinHeapNode* extractMin(struct MinHeap* minHeap) 120 | 121 | { 122 | 123 | struct MinHeapNode* temp = minHeap->array[0]; 124 | minHeap->array[0] 125 | = minHeap->array[minHeap->size - 1]; 126 | 127 | --minHeap->size; 128 | minHeapify(minHeap, 0); 129 | 130 | return temp; 131 | } 132 | 133 | // A utility function to insert 134 | // a new node to Min Heap 135 | void insertMinHeap(struct MinHeap* minHeap, 136 | struct MinHeapNode* minHeapNode) 137 | 138 | { 139 | 140 | ++minHeap->size; 141 | int i = minHeap->size - 1; 142 | 143 | while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { 144 | 145 | minHeap->array[i] = minHeap->array[(i - 1) / 2]; 146 | i = (i - 1) / 2; 147 | } 148 | 149 | minHeap->array[i] = minHeapNode; 150 | } 151 | 152 | // A standard function to build min heap 153 | void buildMinHeap(struct MinHeap* minHeap) 154 | 155 | { 156 | 157 | int n = minHeap->size - 1; 158 | int i; 159 | 160 | for (i = (n - 1) / 2; i >= 0; --i) 161 | minHeapify(minHeap, i); 162 | } 163 | 164 | // A utility function to print an array of size n 165 | void printArr(int arr[], int n) 166 | { 167 | int i; 168 | for (i = 0; i < n; ++i) 169 | cout<< arr[i]; 170 | 171 | cout<<"\n"; 172 | } 173 | 174 | // Utility function to check if this node is leaf 175 | int isLeaf(struct MinHeapNode* root) 176 | 177 | { 178 | 179 | return !(root->left) && !(root->right); 180 | } 181 | 182 | // Creates a min heap of capacity 183 | // equal to size and inserts all character of 184 | // data[] in min heap. Initially size of 185 | // min heap is equal to capacity 186 | struct MinHeap* createAndBuildMinHeap(char data[], int freq[], int size) 187 | 188 | { 189 | 190 | struct MinHeap* minHeap = createMinHeap(size); 191 | 192 | for (int i = 0; i < size; ++i) 193 | minHeap->array[i] = newNode(data[i], freq[i]); 194 | 195 | minHeap->size = size; 196 | buildMinHeap(minHeap); 197 | 198 | return minHeap; 199 | } 200 | 201 | // The main function that builds Huffman tree 202 | struct MinHeapNode* buildHuffmanTree(char data[], int freq[], int size) 203 | 204 | { 205 | struct MinHeapNode *left, *right, *top; 206 | 207 | // Step 1: Create a min heap of capacity 208 | // equal to size. Initially, there are 209 | // modes equal to size. 210 | struct MinHeap* minHeap = createAndBuildMinHeap(data, freq, size); 211 | 212 | // Iterate while size of heap doesn't become 1 213 | while (!isSizeOne(minHeap)) { 214 | 215 | // Step 2: Extract the two minimum 216 | // freq items from min heap 217 | left = extractMin(minHeap); 218 | right = extractMin(minHeap); 219 | 220 | // Step 3: Create a new internal 221 | // node with frequency equal to the 222 | // sum of the two nodes frequencies. 223 | // Make the two extracted node as 224 | // left and right children of this new node. 225 | // Add this node to the min heap 226 | // '$' is a special value for internal nodes, not used 227 | top = newNode('$', left->freq + right->freq); 228 | 229 | top->left = left; 230 | top->right = right; 231 | 232 | insertMinHeap(minHeap, top); 233 | } 234 | 235 | // Step 4: The remaining node is the 236 | // root node and the tree is complete. 237 | return extractMin(minHeap); 238 | } 239 | 240 | // Prints huffman codes from the root of Huffman Tree. 241 | // It uses arr[] to store codes 242 | void printCodes(struct MinHeapNode* root, int arr[], int top) 243 | 244 | { 245 | 246 | // Assign 0 to left edge and recur 247 | if (root->left) { 248 | 249 | arr[top] = 0; 250 | printCodes(root->left, arr, top + 1); 251 | } 252 | 253 | // Assign 1 to right edge and recur 254 | if (root->right) { 255 | 256 | arr[top] = 1; 257 | printCodes(root->right, arr, top + 1); 258 | } 259 | 260 | // If this is a leaf node, then 261 | // it contains one of the input 262 | // characters, print the character 263 | // and its code from arr[] 264 | if (isLeaf(root)) { 265 | 266 | cout<< root->data <<": "; 267 | printArr(arr, top); 268 | } 269 | } 270 | 271 | // The main function that builds a 272 | // Huffman Tree and print codes by traversing 273 | // the built Huffman Tree 274 | void HuffmanCodes(char data[], int freq[], int size) 275 | 276 | { 277 | // Construct Huffman Tree 278 | struct MinHeapNode* root 279 | = buildHuffmanTree(data, freq, size); 280 | 281 | // Print Huffman codes using 282 | // the Huffman tree built above 283 | int arr[MAX_TREE_HT], top = 0; 284 | 285 | printCodes(root, arr, top); 286 | } 287 | 288 | // Driver code 289 | int main() 290 | { 291 | 292 | char arr[] = { 'a', 'b', 'c', 'd', 'e', 'f' }; 293 | int freq[] = { 5, 9, 12, 13, 16, 45 }; 294 | 295 | int size = sizeof(arr) / sizeof(arr[0]); 296 | 297 | HuffmanCodes(arr, freq, size); 298 | 299 | return 0; 300 | } 301 | -------------------------------------------------------------------------------- /davl.cpp: -------------------------------------------------------------------------------- 1 | // C++ program to delete a node from AVL Tree 2 | #include 3 | using namespace std; 4 | 5 | // An AVL tree node 6 | class Node 7 | { 8 | public: 9 | int key; 10 | Node *left; 11 | Node *right; 12 | int height; 13 | }; 14 | 15 | // A utility function to get maximum 16 | // of two integers 17 | int max(int a, int b); 18 | 19 | // A utility function to get height 20 | // of the tree 21 | int height(Node *N) 22 | { 23 | if (N == NULL) 24 | return 0; 25 | return N->height; 26 | } 27 | 28 | // A utility function to get maximum 29 | // of two integers 30 | int max(int a, int b) 31 | { 32 | return (a > b)? a : b; 33 | } 34 | 35 | /* Helper function that allocates a 36 | new node with the given key and 37 | NULL left and right pointers. */ 38 | Node* newNode(int key) 39 | { 40 | Node* node = new Node(); 41 | node->key = key; 42 | node->left = NULL; 43 | node->right = NULL; 44 | node->height = 1; // new node is initially 45 | // added at leaf 46 | return(node); 47 | } 48 | 49 | // A utility function to right 50 | // rotate subtree rooted with y 51 | // See the diagram given above. 52 | Node *rightRotate(Node *y) 53 | { 54 | Node *x = y->left; 55 | Node *T2 = x->right; 56 | 57 | // Perform rotation 58 | x->right = y; 59 | y->left = T2; 60 | 61 | // Update heights 62 | y->height = max(height(y->left), 63 | height(y->right)) + 1; 64 | x->height = max(height(x->left), 65 | height(x->right)) + 1; 66 | 67 | // Return new root 68 | return x; 69 | } 70 | 71 | // A utility function to left 72 | // rotate subtree rooted with x 73 | // See the diagram given above. 74 | Node *leftRotate(Node *x) 75 | { 76 | Node *y = x->right; 77 | Node *T2 = y->left; 78 | 79 | // Perform rotation 80 | y->left = x; 81 | x->right = T2; 82 | 83 | // Update heights 84 | x->height = max(height(x->left), 85 | height(x->right)) + 1; 86 | y->height = max(height(y->left), 87 | height(y->right)) + 1; 88 | 89 | // Return new root 90 | return y; 91 | } 92 | 93 | // Get Balance factor of node N 94 | int getBalance(Node *N) 95 | { 96 | if (N == NULL) 97 | return 0; 98 | return height(N->left) - 99 | height(N->right); 100 | } 101 | 102 | Node* insert(Node* node, int key) 103 | { 104 | /* 1. Perform the normal BST rotation */ 105 | if (node == NULL) 106 | return(newNode(key)); 107 | 108 | if (key < node->key) 109 | node->left = insert(node->left, key); 110 | else if (key > node->key) 111 | node->right = insert(node->right, key); 112 | else // Equal keys not allowed 113 | return node; 114 | 115 | /* 2. Update height of this ancestor node */ 116 | node->height = 1 + max(height(node->left), 117 | height(node->right)); 118 | 119 | /* 3. Get the balance factor of this 120 | ancestor node to check whether 121 | this node became unbalanced */ 122 | int balance = getBalance(node); 123 | 124 | // If this node becomes unbalanced, 125 | // then there are 4 cases 126 | 127 | // Left Left Case 128 | if (balance > 1 && key < node->left->key) 129 | return rightRotate(node); 130 | 131 | // Right Right Case 132 | if (balance < -1 && key > node->right->key) 133 | return leftRotate(node); 134 | 135 | // Left Right Case 136 | if (balance > 1 && key > node->left->key) 137 | { 138 | node->left = leftRotate(node->left); 139 | return rightRotate(node); 140 | } 141 | 142 | // Right Left Case 143 | if (balance < -1 && key < node->right->key) 144 | { 145 | node->right = rightRotate(node->right); 146 | return leftRotate(node); 147 | } 148 | 149 | /* return the (unchanged) node pointer */ 150 | return node; 151 | } 152 | 153 | /* Given a non-empty binary search tree, 154 | return the node with minimum key value 155 | found in that tree. Note that the entire 156 | tree does not need to be searched. */ 157 | Node * minValueNode(Node* node) 158 | { 159 | Node* current = node; 160 | 161 | /* loop down to find the leftmost leaf */ 162 | while (current->left != NULL) 163 | current = current->left; 164 | 165 | return current; 166 | } 167 | 168 | // Recursive function to delete a node 169 | // with given key from subtree with 170 | // given root. It returns root of the 171 | // modified subtree. 172 | Node* deleteNode(Node* root, int key) 173 | { 174 | 175 | // STEP 1: PERFORM STANDARD BST DELETE 176 | if (root == NULL) 177 | return root; 178 | 179 | // If the key to be deleted is smaller 180 | // than the root's key, then it lies 181 | // in left subtree 182 | if ( key < root->key ) 183 | root->left = deleteNode(root->left, key); 184 | 185 | // If the key to be deleted is greater 186 | // than the root's key, then it lies 187 | // in right subtree 188 | else if( key > root->key ) 189 | root->right = deleteNode(root->right, key); 190 | 191 | // if key is same as root's key, then 192 | // This is the node to be deleted 193 | else 194 | { 195 | // node with only one child or no child 196 | if( (root->left == NULL) || 197 | (root->right == NULL) ) 198 | { 199 | Node *temp = root->left ? 200 | root->left : 201 | root->right; 202 | 203 | // No child case 204 | if (temp == NULL) 205 | { 206 | temp = root; 207 | root = NULL; 208 | } 209 | else // One child case 210 | *root = *temp; // Copy the contents of 211 | // the non-empty child 212 | free(temp); 213 | } 214 | else 215 | { 216 | // node with two children: Get the inorder 217 | // successor (smallest in the right subtree) 218 | Node* temp = minValueNode(root->right); 219 | 220 | // Copy the inorder successor's 221 | // data to this node 222 | root->key = temp->key; 223 | 224 | // Delete the inorder successor 225 | root->right = deleteNode(root->right, 226 | temp->key); 227 | } 228 | } 229 | 230 | // If the tree had only one node 231 | // then return 232 | if (root == NULL) 233 | return root; 234 | 235 | // STEP 2: UPDATE HEIGHT OF THE CURRENT NODE 236 | root->height = 1 + max(height(root->left), 237 | height(root->right)); 238 | 239 | // STEP 3: GET THE BALANCE FACTOR OF 240 | // THIS NODE (to check whether this 241 | // node became unbalanced) 242 | int balance = getBalance(root); 243 | 244 | // If this node becomes unbalanced, 245 | // then there are 4 cases 246 | 247 | // Left Left Case 248 | if (balance > 1 && 249 | getBalance(root->left) >= 0) 250 | return rightRotate(root); 251 | 252 | // Left Right Case 253 | if (balance > 1 && 254 | getBalance(root->left) < 0) 255 | { 256 | root->left = leftRotate(root->left); 257 | return rightRotate(root); 258 | } 259 | 260 | // Right Right Case 261 | if (balance < -1 && 262 | getBalance(root->right) <= 0) 263 | return leftRotate(root); 264 | 265 | // Right Left Case 266 | if (balance < -1 && 267 | getBalance(root->right) > 0) 268 | { 269 | root->right = rightRotate(root->right); 270 | return leftRotate(root); 271 | } 272 | 273 | return root; 274 | } 275 | 276 | // A utility function to print preorder 277 | // traversal of the tree. 278 | // The function also prints height 279 | // of every node 280 | void preOrder(Node *root) 281 | { 282 | if(root != NULL) 283 | { 284 | cout << root->key << " "; 285 | preOrder(root->left); 286 | preOrder(root->right); 287 | } 288 | } 289 | 290 | // Driver Code 291 | int main() 292 | { 293 | Node *root = NULL; 294 | 295 | /* Constructing tree given in 296 | the above figure */ 297 | root = insert(root, 9); 298 | root = insert(root, 5); 299 | root = insert(root, 10); 300 | root = insert(root, 0); 301 | root = insert(root, 6); 302 | root = insert(root, 11); 303 | root = insert(root, -1); 304 | root = insert(root, 1); 305 | root = insert(root, 2); 306 | 307 | /* The constructed AVL Tree would be 308 | 9 309 | / \ 310 | 1 10 311 | / \ \ 312 | 0 5 11 313 | / / \ 314 | -1 2 6 315 | */ 316 | 317 | cout << "Preorder traversal of the " 318 | "constructed AVL tree is \n"; 319 | preOrder(root); 320 | 321 | root = deleteNode(root, 10); 322 | 323 | /* The AVL Tree after deletion of 10 324 | 1 325 | / \ 326 | 0 9 327 | / / \ 328 | -1 5 11 329 | / \ 330 | 2 6 331 | */ 332 | 333 | cout << "\nPreorder traversal after" 334 | << " deletion of 10 \n"; 335 | preOrder(root); 336 | 337 | return 0; 338 | } 339 | 340 | // This code is contributed by rathbhupendra 341 | -------------------------------------------------------------------------------- /redblack.cpp: -------------------------------------------------------------------------------- 1 | #include 2 | #include 3 | using namespace std; 4 | 5 | enum COLOR { RED, BLACK }; 6 | 7 | class Node { 8 | public: 9 | int val; 10 | COLOR color; 11 | Node *left, *right, *parent; 12 | 13 | Node(int val) : val(val) { 14 | parent = left = right = NULL; 15 | 16 | // Node is created during insertion 17 | // Node is red at insertion 18 | color = RED; 19 | } 20 | 21 | // returns pointer to uncle 22 | Node *uncle() { 23 | // If no parent or grandparent, then no uncle 24 | if (parent == NULL or parent->parent == NULL) 25 | return NULL; 26 | 27 | if (parent->isOnLeft()) 28 | // uncle on right 29 | return parent->parent->right; 30 | else 31 | // uncle on left 32 | return parent->parent->left; 33 | } 34 | 35 | // check if node is left child of parent 36 | bool isOnLeft() { return this == parent->left; } 37 | 38 | // returns pointer to sibling 39 | Node *sibling() { 40 | // sibling null if no parent 41 | if (parent == NULL) 42 | return NULL; 43 | 44 | if (isOnLeft()) 45 | return parent->right; 46 | 47 | return parent->left; 48 | } 49 | 50 | // moves node down and moves given node in its place 51 | void moveDown(Node *nParent) { 52 | if (parent != NULL) { 53 | if (isOnLeft()) { 54 | parent->left = nParent; 55 | } else { 56 | parent->right = nParent; 57 | } 58 | } 59 | nParent->parent = parent; 60 | parent = nParent; 61 | } 62 | 63 | bool hasRedChild() { 64 | return (left != NULL and left->color == RED) or 65 | (right != NULL and right->color == RED); 66 | } 67 | }; 68 | 69 | class RBTree { 70 | Node *root; 71 | 72 | // left rotates the given node 73 | void leftRotate(Node *x) { 74 | // new parent will be node's right child 75 | Node *nParent = x->right; 76 | 77 | // update root if current node is root 78 | if (x == root) 79 | root = nParent; 80 | 81 | x->moveDown(nParent); 82 | 83 | // connect x with new parent's left element 84 | x->right = nParent->left; 85 | // connect new parent's left element with node 86 | // if it is not null 87 | if (nParent->left != NULL) 88 | nParent->left->parent = x; 89 | 90 | // connect new parent with x 91 | nParent->left = x; 92 | } 93 | 94 | void rightRotate(Node *x) { 95 | // new parent will be node's left child 96 | Node *nParent = x->left; 97 | 98 | // update root if current node is root 99 | if (x == root) 100 | root = nParent; 101 | 102 | x->moveDown(nParent); 103 | 104 | // connect x with new parent's right element 105 | x->left = nParent->right; 106 | // connect new parent's right element with node 107 | // if it is not null 108 | if (nParent->right != NULL) 109 | nParent->right->parent = x; 110 | 111 | // connect new parent with x 112 | nParent->right = x; 113 | } 114 | 115 | void swapColors(Node *x1, Node *x2) { 116 | COLOR temp; 117 | temp = x1->color; 118 | x1->color = x2->color; 119 | x2->color = temp; 120 | } 121 | 122 | void swapValues(Node *u, Node *v) { 123 | int temp; 124 | temp = u->val; 125 | u->val = v->val; 126 | v->val = temp; 127 | } 128 | 129 | // fix red red at given node 130 | void fixRedRed(Node *x) { 131 | // if x is root color it black and return 132 | if (x == root) { 133 | x->color = BLACK; 134 | return; 135 | } 136 | 137 | // initialize parent, grandparent, uncle 138 | Node *parent = x->parent, *grandparent = parent->parent, 139 | *uncle = x->uncle(); 140 | 141 | if (parent->color != BLACK) { 142 | if (uncle != NULL && uncle->color == RED) { 143 | // uncle red, perform recoloring and recurse 144 | parent->color = BLACK; 145 | uncle->color = BLACK; 146 | grandparent->color = RED; 147 | fixRedRed(grandparent); 148 | } else { 149 | // Else perform LR, LL, RL, RR 150 | if (parent->isOnLeft()) { 151 | if (x->isOnLeft()) { 152 | // for left right 153 | swapColors(parent, grandparent); 154 | } else { 155 | leftRotate(parent); 156 | swapColors(x, grandparent); 157 | } 158 | // for left left and left right 159 | rightRotate(grandparent); 160 | } else { 161 | if (x->isOnLeft()) { 162 | // for right left 163 | rightRotate(parent); 164 | swapColors(x, grandparent); 165 | } else { 166 | swapColors(parent, grandparent); 167 | } 168 | 169 | // for right right and right left 170 | leftRotate(grandparent); 171 | } 172 | } 173 | } 174 | } 175 | 176 | // find node that do not have a left child 177 | // in the subtree of the given node 178 | Node *successor(Node *x) { 179 | Node *temp = x; 180 | 181 | while (temp->left != NULL) 182 | temp = temp->left; 183 | 184 | return temp; 185 | } 186 | 187 | // find node that replaces a deleted node in BST 188 | Node *BSTreplace(Node *x) { 189 | // when node have 2 children 190 | if (x->left != NULL and x->right != NULL) 191 | return successor(x->right); 192 | 193 | // when leaf 194 | if (x->left == NULL and x->right == NULL) 195 | return NULL; 196 | 197 | // when single child 198 | if (x->left != NULL) 199 | return x->left; 200 | else 201 | return x->right; 202 | } 203 | 204 | // deletes the given node 205 | void deleteNode(Node *v) { 206 | Node *u = BSTreplace(v); 207 | 208 | // True when u and v are both black 209 | bool uvBlack = ((u == NULL or u->color == BLACK) and (v->color == BLACK)); 210 | Node *parent = v->parent; 211 | 212 | if (u == NULL) { 213 | // u is NULL therefore v is leaf 214 | if (v == root) { 215 | // v is root, making root null 216 | root = NULL; 217 | } else { 218 | if (uvBlack) { 219 | // u and v both black 220 | // v is leaf, fix double black at v 221 | fixDoubleBlack(v); 222 | } else { 223 | // u or v is red 224 | if (v->sibling() != NULL) 225 | // sibling is not null, make it red" 226 | v->sibling()->color = RED; 227 | } 228 | 229 | // delete v from the tree 230 | if (v->isOnLeft()) { 231 | parent->left = NULL; 232 | } else { 233 | parent->right = NULL; 234 | } 235 | } 236 | delete v; 237 | return; 238 | } 239 | 240 | if (v->left == NULL or v->right == NULL) { 241 | // v has 1 child 242 | if (v == root) { 243 | // v is root, assign the value of u to v, and delete u 244 | v->val = u->val; 245 | v->left = v->right = NULL; 246 | delete u; 247 | } else { 248 | // Detach v from tree and move u up 249 | if (v->isOnLeft()) { 250 | parent->left = u; 251 | } else { 252 | parent->right = u; 253 | } 254 | delete v; 255 | u->parent = parent; 256 | if (uvBlack) { 257 | // u and v both black, fix double black at u 258 | fixDoubleBlack(u); 259 | } else { 260 | // u or v red, color u black 261 | u->color = BLACK; 262 | } 263 | } 264 | return; 265 | } 266 | 267 | // v has 2 children, swap values with successor and recurse 268 | swapValues(u, v); 269 | deleteNode(u); 270 | } 271 | 272 | void fixDoubleBlack(Node *x) { 273 | if (x == root) 274 | // Reached root 275 | return; 276 | 277 | Node *sibling = x->sibling(), *parent = x->parent; 278 | if (sibling == NULL) { 279 | // No sibiling, double black pushed up 280 | fixDoubleBlack(parent); 281 | } else { 282 | if (sibling->color == RED) { 283 | // Sibling red 284 | parent->color = RED; 285 | sibling->color = BLACK; 286 | if (sibling->isOnLeft()) { 287 | // left case 288 | rightRotate(parent); 289 | } else { 290 | // right case 291 | leftRotate(parent); 292 | } 293 | fixDoubleBlack(x); 294 | } else { 295 | // Sibling black 296 | if (sibling->hasRedChild()) { 297 | // at least 1 red children 298 | if (sibling->left != NULL and sibling->left->color == RED) { 299 | if (sibling->isOnLeft()) { 300 | // left left 301 | sibling->left->color = sibling->color; 302 | sibling->color = parent->color; 303 | rightRotate(parent); 304 | } else { 305 | // right left 306 | sibling->left->color = parent->color; 307 | rightRotate(sibling); 308 | leftRotate(parent); 309 | } 310 | } else { 311 | if (sibling->isOnLeft()) { 312 | // left right 313 | sibling->right->color = parent->color; 314 | leftRotate(sibling); 315 | rightRotate(parent); 316 | } else { 317 | // right right 318 | sibling->right->color = sibling->color; 319 | sibling->color = parent->color; 320 | leftRotate(parent); 321 | } 322 | } 323 | parent->color = BLACK; 324 | } else { 325 | // 2 black children 326 | sibling->color = RED; 327 | if (parent->color == BLACK) 328 | fixDoubleBlack(parent); 329 | else 330 | parent->color = BLACK; 331 | } 332 | } 333 | } 334 | } 335 | 336 | // prints level order for given node 337 | void levelOrder(Node *x) { 338 | if (x == NULL) 339 | // return if node is null 340 | return; 341 | 342 | // queue for level order 343 | queue q; 344 | Node *curr; 345 | 346 | // push x 347 | q.push(x); 348 | 349 | while (!q.empty()) { 350 | // while q is not empty 351 | // dequeue 352 | curr = q.front(); 353 | q.pop(); 354 | 355 | // print node value 356 | cout << curr->val << " "; 357 | 358 | // push children to queue 359 | if (curr->left != NULL) 360 | q.push(curr->left); 361 | if (curr->right != NULL) 362 | q.push(curr->right); 363 | } 364 | } 365 | 366 | // prints inorder recursively 367 | void inorder(Node *x) { 368 | if (x == NULL) 369 | return; 370 | inorder(x->left); 371 | cout << x->val << " "; 372 | inorder(x->right); 373 | } 374 | 375 | public: 376 | // constructor 377 | // initialize root 378 | RBTree() { root = NULL; } 379 | 380 | Node *getRoot() { return root; } 381 | 382 | // searches for given value 383 | // if found returns the node (used for delete) 384 | // else returns the last node while traversing (used in insert) 385 | Node *search(int n) { 386 | Node *temp = root; 387 | while (temp != NULL) { 388 | if (n < temp->val) { 389 | if (temp->left == NULL) 390 | break; 391 | else 392 | temp = temp->left; 393 | } else if (n == temp->val) { 394 | break; 395 | } else { 396 | if (temp->right == NULL) 397 | break; 398 | else 399 | temp = temp->right; 400 | } 401 | } 402 | 403 | return temp; 404 | } 405 | 406 | // inserts the given value to tree 407 | void insert(int n) { 408 | Node *newNode = new Node(n); 409 | if (root == NULL) { 410 | // when root is null 411 | // simply insert value at root 412 | newNode->color = BLACK; 413 | root = newNode; 414 | } else { 415 | Node *temp = search(n); 416 | 417 | if (temp->val == n) { 418 | // return if value already exists 419 | return; 420 | } 421 | 422 | // if value is not found, search returns the node 423 | // where the value is to be inserted 424 | 425 | // connect new node to correct node 426 | newNode->parent = temp; 427 | 428 | if (n < temp->val) 429 | temp->left = newNode; 430 | else 431 | temp->right = newNode; 432 | 433 | // fix red red voilaton if exists 434 | fixRedRed(newNode); 435 | } 436 | } 437 | 438 | // utility function that deletes the node with given value 439 | void deleteByVal(int n) { 440 | if (root == NULL) 441 | // Tree is empty 442 | return; 443 | 444 | Node *v = search(n), *u; 445 | 446 | if (v->val != n) { 447 | cout << "No node found to delete with value:" << n << endl; 448 | return; 449 | } 450 | 451 | deleteNode(v); 452 | } 453 | 454 | // prints inorder of the tree 455 | void printInOrder() { 456 | cout << "Inorder: " << endl; 457 | if (root == NULL) 458 | cout << "Tree is empty" << endl; 459 | else 460 | inorder(root); 461 | cout << endl; 462 | } 463 | 464 | // prints level order of the tree 465 | void printLevelOrder() { 466 | cout << "Level order: " << endl; 467 | if (root == NULL) 468 | cout << "Tree is empty" << endl; 469 | else 470 | levelOrder(root); 471 | cout << endl; 472 | } 473 | }; 474 | 475 | int main() { 476 | RBTree tree; 477 | 478 | tree.insert(7); 479 | tree.insert(3); 480 | tree.insert(18); 481 | tree.insert(10); 482 | tree.insert(22); 483 | tree.insert(8); 484 | tree.insert(11); 485 | tree.insert(26); 486 | tree.insert(2); 487 | tree.insert(6); 488 | tree.insert(13); 489 | 490 | tree.printInOrder(); 491 | tree.printLevelOrder(); 492 | 493 | cout<