From 5315639c58c902cc18374212477006cface66e6e Mon Sep 17 00:00:00 2001 From: Aadit Agrawal Date: Tue, 22 Oct 2024 08:48:58 +0530 Subject: [PATCH] Upload files to "DS/C/Lab/Shortcodes" --- DS/C/Lab/Shortcodes/polyadds.c | 50 +++++++++++++++++++++++++++++++++ DS/C/Lab/Shortcodes/recurtree.c | 34 ++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 DS/C/Lab/Shortcodes/polyadds.c create mode 100644 DS/C/Lab/Shortcodes/recurtree.c diff --git a/DS/C/Lab/Shortcodes/polyadds.c b/DS/C/Lab/Shortcodes/polyadds.c new file mode 100644 index 0000000..b448972 --- /dev/null +++ b/DS/C/Lab/Shortcodes/polyadds.c @@ -0,0 +1,50 @@ +#include +#include + +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; +} diff --git a/DS/C/Lab/Shortcodes/recurtree.c b/DS/C/Lab/Shortcodes/recurtree.c new file mode 100644 index 0000000..52126e8 --- /dev/null +++ b/DS/C/Lab/Shortcodes/recurtree.c @@ -0,0 +1,34 @@ +#include +#include +#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(vd)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; +}