Upload files to "DS/C/Lab/Shortcodes"

This commit is contained in:
Aadit Agrawal 2024-10-22 08:48:58 +05:30
parent 4d3da88635
commit 5315639c58
2 changed files with 84 additions and 0 deletions

View File

@ -0,0 +1,50 @@
#include <stdio.h>
#include <stdlib.h>
typedef struct p { int c, e; struct p *n; } *P;
P new_p(int c, int e) {
P t = malloc(sizeof(struct p));
t->c = c; t->e = e; t->n = NULL; return t;
}
void insert_end(int c, int e, P *h) {
P t = new_p(c, e);
if (!*h) *h = t;
else { P cur = *h; while (cur->n) cur = cur->n; cur->n = t; }
}
void attach(int c, int e, P *r) {
(*r)->n = new_p(c, e); *r = (*r)->n;
}
P poly_add(P A, P B) {
P r = new_p(0, 0), C = r;
while (A && B) {
int d = A->e - B->e;
if (d < 0) { attach(B->c, B->e, &r); B = B->n; }
else if (d > 0) { attach(A->c, A->e, &r); A = A->n; }
else { int s = A->c + B->c; if (s) attach(s, A->e, &r); A = A->n; B = B->n; }
}
for (; A; A = A->n) attach(A->c, A->e, &r);
for (; B; B = B->n) attach(B->c, B->e, &r);
P t = C; C = C->n; free(t); return C;
}
void print_poly(P p) {
if (!p) return;
printf("%dx^%d", p->c, p->e);
for (p = p->n; p; p = p->n) printf(" + %dx^%d", p->c, p->e);
printf("\n");
}
int main() {
P A = NULL, B = NULL;
insert_end(3, 3, &A); insert_end(4, 2, &A); insert_end(1, 0, &A);
printf("1st Polynomial: "); print_poly(A);
insert_end(6, 4, &B); insert_end(5, 2, &B); insert_end(4, 1, &B);
printf("2nd Polynomial: "); print_poly(B);
P C = poly_add(A, B);
printf("Added Polynomial: "); print_poly(C);
return 0;
}

View File

@ -0,0 +1,34 @@
#include<stdio.h>
#include<stdlib.h>
#define M 100
typedef struct N *P;
typedef struct N{int d;P l,r;}N;P root;
int t=-1;P stk[M];
P cn(int v){P n=malloc(sizeof(N));n->d=v;n->l=n->r=NULL;return n;}
P cr(P r,int v){
if(!r)return cn(v);
if(v<r->d)r->l=cr(r->l,v);
else if(v>r->d)r->r=cr(r->r,v);
return r;
}
void po(P r){if(r){po(r->l);po(r->r);printf("%d ",r->d);}}
void pr(P r){if(r){printf("%d ",r->d);pr(r->l);pr(r->r);}}
void io(P r){if(r){io(r->l);printf("%d ",r->d);io(r->r);}}
int main(){
root=cr(root,6);
root=cr(root,4);
root=cr(root,83);
root=cr(root,25);
root=cr(root,42);
printf("Binary Tree (In-Order): ");io(root);puts("");
printf("Binary Tree (Pre-Order): ");pr(root);puts("");
printf("Binary Tree (Post-Order): ");po(root);puts("");
return 0;
}