Wednesday, January 31, 2024

Displaying a Tree - both Recursive and Non Recursive methods - DSTC using C Language (Source Code Implemented)

Displaying a Tree - both Recursive and Non Recursive methods

/*tree traversal inorder,preorder,postorder with recursive and nonrecursive*/


#include<stdio.h>
#include<alloc.h>
#include<conio.h>
typedef struct s
{    int val;
    struct s *left,*right;
}node;

typedef struct ss
{    node *root;
}tree;

tree* maktr(void)
{
tree* t;
t=(tree*)malloc(sizeof(tree));
t->root=NULL;
return t;
}

void instr(tree *t,int v)
{
node *newn,*nd,*par;
nd=t->root;
newn=(node*)malloc(sizeof(node));
newn->val=v;
newn->left=newn->right=NULL;
if(nd==NULL)//tree is empty
{    t->root=newn;
    return;
}
while(nd!=NULL)
{ if(v<nd->val)
  { par=nd;
    nd=nd->left;
  }
  else if(v>nd->val)
  { par=nd;
    nd=nd->right;
  }
else
{
  printf("\n the node with same exists");
  return;
}
}
if(v<par->val)
  par->left=newn;
else
  par->right=newn;
}

node *instr1(node *nd,int v)
{
if(nd==NULL)
{  nd=(node*)malloc(sizeof(node));
  nd->val=v;
  nd->left=nd->right=NULL;
}
else if(v<nd->val)
  nd->left=instr1(nd->left,v);
else
  nd->right=instr1(nd->right,v);
return nd;
}

void inrdsp(node *nd)
{ if(nd)
  { inrdsp(nd->left);
    printf(" %d",nd->val);
    inrdsp(nd->right);
  }
}

void predsp(node *nd)
{ if(nd)
  { printf(" %d",nd->val);
    predsp(nd->left);
    predsp(nd->right);
  }
}

void posdsp(node *nd)
{ if(nd)
  { posdsp(nd->left);
    posdsp(nd->right);
    printf(" %d",nd->val);
  }
}

typedef struct st
{ node *info;
  struct st *next;
}node1;

typedef struct st1
{  node1 *top;
}stack;

stack* crst(void)
{
stack *st;
st=(stack*)malloc(sizeof(stack));
st->top=NULL;
return st;
}

void pushst(stack* st,node *kv)
{
node1* newn;
newn=(node1*)malloc(sizeof(node1));
newn->info=kv;
newn->next=NULL;
if(st->top==NULL)
  st->top =newn;
else
{ newn->next=st->top;
  st->top=newn;
}
}

node* popst(stack* s)
{ node *p;
if(s->top==NULL)
{ printf("\n The stack is empty");
  return NULL;
}
p=s->top->info;
s->top=s->top->next;
return p;
}

void pretrav(tree *t)
{
node *nk=t->root;
stack *s=crst();
do
{
while(nk!=NULL)
{ printf(" %d",nk->val);
  if(nk->right!=NULL)
    pushst(s,nk->right);
  nk=nk->left;
}
if(s->top!=NULL)
  nk=popst(s);
else
  nk=NULL;
}while(nk!=NULL);//end while
}

void inrtrav(tree *t)
{
node *k=t->root;
stack* s=crst();
while(k!=NULL)
{ while(k!=NULL)
  { pushst(s,k);
    k=k->left;
  }
while(s->top!=NULL)
{
k=popst(s);
printf(" %d",k->val);
if(k->right!=NULL)
  { k=k->right; break;
  }
else
  k=NULL;
}// end while 2
}//end while 1
}

void postrav(tree *t)
{
node *nk=t->root,*nk1;
stack *s=crst();
do
{
  while(nk!=NULL)
  {
    pushst(s,nk);
    if(nk->right!=NULL)
    { nk1=nk->right;
      nk1->val=-nk1->val;
      pushst(s,nk1);
    }
    nk=nk->left;
  }
  while(s->top!=NULL)
    { nk=popst(s);
      if(nk->val>=0)
    printf(" %d",nk->val);
      else
      {  nk->val=-nk->val;
      break;
      }
    }
}while(s->top!=NULL);
}
void main()
{
tree *t;
int v,i;
t=maktr();
clrscr();
for(i=0;i<5;i++)
{
printf("\n Enter the value of node");
scanf("%d",&v);
t->root=instr1(t->root,v);
}
printf("\nThe inorder display of the tree\n");
inrdsp(t->root);
printf("\nThe preorder display of the tree\n");
predsp(t->root);
printf("\nThe postorder display of the tree\n");
posdsp(t->root);
printf("\nThe inorder display of the tree\n");
inrtrav(t);
printf("\nThe preorder display of the tree\n");
pretrav(t);
printf("\nThe postorder display of the tree\n");
postrav(t);
getch();
}

 

C++ Stack implementation as a class- DSTC using C Language (Source Code Implemented)

Stack implementation as a class


 

# include<iostream.h>

# include<process.h>

# include<conio.h>

# define SIZE 20

 

class stack

{

      int a[SIZE];

      int tos; // Top of Stack

public:

      stack();

      void push(int);

      int pop();

      int isempty();

      int isfull();

};

stack::stack()

{

      tos=0; //Initialize Top of Stack

}

 

int stack::isempty()

{

      return (tos==0?1:0);

}

int stack::isfull()

{

      return (tos==SIZE?1:0);

}

 

void stack::push(int i)

{

      if(!isfull())

      {

            a[tos]=i;

            tos++;

      }

      else

      {

            cerr<<"Stack overflow error !

                  Possible Data Loss !";

      }

}

int stack::pop()

{

      if(!isempty())

      {

            return(a[--tos]);

      }

      else

      {

            cerr<<"Stack is empty! What to pop...!";

      }

      return 0;

}

 

void main()

{

      stack s;

      int ch=1,num;

      while(ch!=0)

      {

            cout<<"Stack Operations Mani Menu

                  1.Push

                  2.Pop

                  3.IsEmpty

                  4.IsFull

                  0.Exit

                  <BR>;

            cin>>ch;

            switch(ch)

            {

            case 0:

                  exit(1); //Normal Termination of Program

            case 1:

                  cout<<"Enter the number to push";

                  cin>>num;

                  s.push(num);

                  break;

            case 2:

                  cout<<"Number popped from the stack is: "<<s.pop()<<endl;

                  break;

            case 3:

                  (s.isempty())?(cout<<"Stack is empty.<BR>):(cout<<"Stack is not empty.<BR>);

                  break;

            case 4:

                  (s.isfull())?(cout<<"Stack is full.<BR>):(cout<<"Stack is not full.<BR>);

                  break;

            default:

                  cout<<"Illegal Option.

                        Please try again<BR>;

            }

      }//end of while

      getch();

}

 

ADJACENCY LIST - Representation of Graph through Adjacency LIST - DSTC using C Language (Source Code Implemented)

ADJACENCY LIST
(Representation of Graph through Adjacency LIST 
)
Implemented using C Language 
 

 


ADJLIST.H

/*  Name     : Adjlist.h
Purpose  : This files defines node structure and all basic Graph opearations
Operations :
Graph * GetGraph(void);
void InsNode(Graph *g, int v);
NodeEdge * FindNode(Graph *g, int v);
void InsEdge(Graph *g, int v, int x);
void print(Graph *s);
void DelEdge(Graph *g, int v, int x);
void DelNode(Graph *g, int v);
void PrintEdge(Graph *g, int v);
void BreadthFirst(Graph *g,int v,int w);
void DepthFirst(Graph *g,char v);           */

#include "stack.h"
#include <string.h>
typedef union nodeedge {
    struct node {
        char info;      //Node name or number
        int status;     //Status of node, status will be 1-Ready State,
        //2-Waiting State and 3-Processed State
        union nodeedge * nextnode;
        union nodeedge * edgeptr;
    }Node;

struct edge {
        union nodeedge * nextedge;
        union nodeedge * nodeptr;
    }Edge;
}NodeEdge;

typedef struct {
    union nodeedge * start;
}Graph;

Graph * GetGraph(void)
{
    Graph *s;
    s=(Graph *)malloc(sizeof(Graph));
    s->start=NULL;
    return s;
}

// operations on Graph
//Inserting a new node in the Graph
void InsNode(Graph *g, char v)
{
    NodeEdge *new1;
    new1=(NodeEdge *)malloc(sizeof(NodeEdge));
    new1->Node.info=v;
    new1->Node.nextnode=g->start;
    new1->Node.edgeptr=NULL;
    new1->Node.status=1;    //Initially status of all the nodes
    //will be 1
    g->start=new1;
}

//Finding a node in the graph
NodeEdge * FindNode(Graph *g, char v)
{
    NodeEdge *temp;
    temp=g->start;
    // printf("Testing(Inside find node): %c\n",v);
    // printf("\nTesting(Inside find node): %c %c\n",v,temp->Node.info);
    while(temp)
    {
        if(temp->Node.info==v)
            break;
        else
            temp=temp->Node.nextnode;
    }
    return temp;
}

//Adding an edge in the graph
void InsEdge(Graph *g, char v, char x)
{
    NodeEdge *newedge, *start, *end;
    newedge=(NodeEdge *)malloc(sizeof(NodeEdge));
    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Starting Node %c does not exist\n",v);
        exit(1);
    }
    end=FindNode(g,x);
    if(end==NULL)
    {
        printf("Ending Node %c does not exist\n",x);
        exit(1);
    }

    newedge->Edge.nextedge=start->Node.edgeptr;
    start->Node.edgeptr=newedge;
    newedge->Edge.nodeptr=end;
}

//Deleting an edge from the graph
void DelEdge(Graph *g, char v, char x)
{
    NodeEdge *start, *end, *q, *q1;
    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Starting Node %c does not exist\n",v);
        exit(1);
    }
    if(start->Node.edgeptr)
    {
        printf("This node does not have any edge\n");
        exit(1);
    }
end=FindNode(g,x);
    if(end==NULL)
    {
        printf("Ending Node %c does not exist\n",x);
        exit(1);
    }

    q=start->Node.edgeptr;
    while(q)
    {
        if(q->Edge.nodeptr==end)
            break;
        else
        {
            q1=q;
            q=q->Edge.nextedge;
        }
    }
if(q==start->Node.edgeptr && q->Edge.nodeptr==end)
    {
        start->Node.edgeptr=q->Edge.nextedge;
        free(q);
    }
    else
    {
        if(q)  //if edge exist only then
        {
            q1->Edge.nextedge=q->Edge.nextedge;
            free(q);
        }
    }
}

//Deleting a node
void DelNode(Graph *g, char v)
{
    NodeEdge *start, *del, *q;
    del=g->start;
    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Node %c does not exist\n",v);
        exit(1);
    }
    while(del) //deleting all the edges pointing to this node if any
    {
        DelEdge(g,del->Node.info, v);
        del=del->Node.nextnode;
    }

    del=g->start;
    while(del)
    {
        if(del->Node.nextnode==start)
        {
            del->Node.nextnode=start->Node.nextnode;
            free(start);
            break;
        }
        del=del->Node.nextnode;
    }
}

//printing all the edges of the node
void PrintEdge(Graph *g, char v)
{
    NodeEdge *q,*q1,*q2;
    q=FindNode(g,v);
    if(q==NULL)
    {
        printf("Node %c does not exist\n",v);
        exit(1);
    }
    printf("----All the edges starting from %c are--->\n",v);
    if(q->Node.edgeptr==NULL)
    {
        printf("This Node does not have any edge\n");
        return;
    }
    else
    {
        q1=q->Node.edgeptr;
        while(q1)
        {
            q2=q1->Edge.nodeptr;
            printf("To Node: %c\n", q2->Node.info);
            q1=q1->Edge.nextedge;
        }
    }
}

//printing the graph
void print(Graph *g)
{
    NodeEdge *t;
    t=g->start;
    while(t)
    {
        PrintEdge(g,t->Node.info);  //printing all the edges of current node
        t=t->Node.nextnode;
        fflush(stdin);
        getchar();
    }
}

//Breadth first algorithm---------------
void BreadthFirst(Graph *g,char v,char w)
{
    NodeEdge *start,*end,*q,*p;
    char c;
    int front,rear;
    int flag=0;
    char *queue,*orig;
    //char *path;
    void detpath(char *a,char *b,int c,char d);

    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Starting Node %c does not exist\n",v);
        exit(1);
    }
    end=FindNode(g,w);
    if(end==NULL)
    {
        printf("Ending Node %c does not exist\n",w);
        exit(1);
    }

    //put starting node in Queue and Change its Status to 2
    front=0;   //initially queue is empty
    queue[front]=start->Node.info;
    orig[front]=' ';
    start->Node.status=2;
    rear=1;

while(front<=rear)
    {
        //remove top node of queue and change its status to 3
        c=queue[front];
        q=FindNode(g,c);
        q->Node.status=3;
        //add to queue all the neighbors of current node whose status is 1
        p=q->Node.edgeptr;
        while(p)
        {
            if(p->Edge.nodeptr->Node.status==1)
            {
                queue[rear]=p->Edge.nodeptr->Node.info;
                orig[rear]=q->Node.info;
                p->Edge.nodeptr->Node.status=2;
                if(queue[rear]==w)  //if target node is found then quit
                {
                    queue[rear+1]='\0';
                    orig[rear+1]='\0';
                    flag=1;
                    break;
                }
                rear++;
            }
            p=p->Edge.nextedge;
        }
        //-------------------------------------------------------------

        if(flag)
        {
            printf("Queue is   : %s\n",queue);
            printf("Originating: %s\n",orig);
            break;
        }
        front++;
    }

    //determining path
    detpath(queue,orig,rear,v);
}

//Finding the position of a info
int find(char *arr,char c)
{
    int i;
for(i=0;i<strlen(arr);i++)
    {
        if(arr[i]==c)
            return i;
    }
    return -1;
}

//determining the path-------------------------
void detpath(char *q,char *o,int r,char st)
{
    char *path;
    int f;
    char c;

    f=0;
    c=o[r];
    path[f++]=q[r];

    //   printf("test: %x %x %x\n",q,o,path);
    while(r>=0 && c!=st)
{
        path[f++]=c;
        r=find(q,c);
        /*       printf("here1:%s %s\n",q,o);
        printf("here2:%d %c %c %c\n",r,c,o[r],o[3]);*/
        c=o[r];
    }
    path[f]=c;
    //displaying path
    while(f>=0)
    {
        printf(" -> %c",path[f]);
        f--;
    }
    fflush(stdin);
    getchar();
}


//Depth first algorithm---------------
void DepthFirst(Graph *g,char v)
{
    NodeEdge *start,*q,*p;
    char c;
    Stack *s;
s=GetStack();
    start=FindNode(g,v);
    if(start==NULL)
    {
        printf("Node %c does not exist\n",v);
        exit(1);
    }

    //push starting node in Stack and Change its Status to 2
    //initially stack is empty
    start->Node.status=2;
    push(s, start->Node.info);
    while(!empty(s))
    {
        //pop top node of stack and change its status to 3
        c=pop(s);
q=FindNode(g,c);
        printf("%c ",q->Node.info);
        q->Node.status=3;
        //push to stack all the neighbors of current node whose status is 1
        p=q->Node.edgeptr;
        while(p)
        {
            if(p->Edge.nodeptr->Node.status==1)
            {
                push(s, p->Edge.nodeptr->Node.info);
                p->Edge.nodeptr->Node.status=2;
            }
            p=p->Edge.nextedge;
        }
        //-------------------------------------------------------------
    }
    fflush(stdin);
    getchar();
}

 


ADJLIST.CPP

/* Name : AdjList.cpp
Purpose: Linked representation of a Graph */
#include <conio.h>
#include "adjlist.h"
void main()
{
    int menu(void);
    Graph *g;
    char c,start,end,info;
    /* char tNode[]="KJGFEDCBA";
    char sNode[]="ABCDEFGJK";
    char eNode[9][4]={"BCF","CG","F","C","JCD","D","EC","KD","GE"};
    int i,j; */
    clrscr();
    g=GetGraph();

   while(1)
    {
        c=menu();
        if(c==8)
            break;
        switch(c) {
case 1:
    printf("Enter Node Number: ");
    fflush(stdin);
    scanf("%c", &info);
    //for(i=0;i<9;i++)
    //InsNode(g,tNode[i]);
    InsNode(g,info);
    break;
case 2:
    printf("Enter Node Number: ");
    fflush(stdin);
    scanf("%c", &info);
    DelNode(g,info);
    break;
case 3:
    printf("Enter starting Node: ");
    fflush(stdin);
    scanf("%c", &start);

    printf("Enter ending Node: ");
    fflush(stdin);
    scanf("%c", &end);

    InsEdge(g,start,end);
    //        }
    //  }
    break;
case 4:
    printf("Enter starting Node: ");
    fflush(stdin);
    scanf("%c", &start);

    printf("Enter ending Node: ");
    fflush(stdin);
    scanf("%c", &end);
    DelEdge(g,start,end);
    break;
case 5:
    print(g);
    break;
case 6:
    printf("Enter starting Node: ");
    fflush(stdin);
    scanf("%c", &start);
printf("Enter ending Node: ");
    fflush(stdin);
    scanf("%c", &end);
    BreadthFirst(g,start,end);
    break;
case 7:
    printf("Enter Node: ");
    fflush(stdin);
    scanf("%c", &start);
    DepthFirst(g,start);
    break;
        }
    }

}

int menu(void)
{
    int ch;
    while(1)
    {
        printf("1. Inserting a Node\n");
        printf("2. Deleting a Node\n");
        printf("3. Inserting an Edge\n");
        printf("4. Deleting an Edge\n");
        printf("5. Printing the Graph\n");
        printf("6. Breadth First Search\n");
        printf("7. Depth First Search\n");
        printf("8. Quit\n");
printf("Enter the choice: ");
        scanf("%d", &ch);
        if(ch<1 || ch > 8)
            printf("Invalid choice\n");
        else
            return ch;
    }
}