Monday 9 April 2012

program in C to store any polynomial using linked list.



#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#define NULL 0
void main()
 {
  struct poly
   {
    int coff;
    int expo;
    struct poly *link;
   }*temp,*start,*n1,*prev;
  int n,i,z=1,num;
  char c;
  clrscr();
  start=NULL;
  n1=NULL;
  printf("\tPOLYNOMIAL CREATION IN LINK LIST AND TRAVERSAL\n\n");
  while(1)
   {
    if(start==NULL)
     {
                temp=(struct poly*)malloc(sizeof(struct poly));
                printf("Enter Coefficient and exponent for Node %d\n",z);
                scanf("%d %d",&temp->coff,&temp->expo);
                start=temp;
                temp->link=NULL;
       }
     else
     {
      temp->link=(struct poly*)malloc(sizeof(struct poly));
      temp=temp->link;
      printf("Enter Coefficient and exponent for Node %d\n",z);
      scanf("%d %d",&temp->coff,&temp->expo);
     }
       z++;
      printf("Do you want to create another node\n");
      fflush(stdin);
      scanf("%c",&c);
      if(c!='y')
       {
                temp->link=NULL;
                break;
       }
     }
   // TARVERSING
  n1=start;
  printf("Traversal\n");
  while(n1!=NULL)
   {
    printf(" %2dx^%d  + ",n1->coff ,n1->expo);
    n1=n1->link;
   }
   printf("\b\b\nTHE END\n");
 getch();
}


Output:

                 POLYNOMIAL CREATION IN LINK LIST AND TRAVERSAL
Enter Coefficient and exponent for Node 1
6
3
Do you want to create another node
Y
Enter Coefficient and exponent for Node 2
8
2
Do u want to create another node
N
Traversal
6x^3  + 8x^2
THE END

2 comments:

  1. how we can write this program in Data structure

    ReplyDelete
  2. include
    #include
    #include
    #define NULL 0
    void main()
    {
    struct poly
    {
    int coff;
    int expo;
    struct poly *link;
    }*temp,*start,*n1,*prev;
    int n,i,z=1,num;
    char c;
    clrscr();
    start=NULL;
    n1=NULL;
    printf("\tPOLYNOMIAL CREATION IN LINK LIST AND TRAVERSAL\n\n");
    while(1)
    {
    if(start==NULL)
    {
    temp=(struct poly*)malloc(sizeof(struct poly));
    printf("Enter Coefficient and exponent for Node %d\n",z);
    scanf("%d %d",&temp->coff,&temp->expo);
    start=temp;
    temp->link=NULL;
    }
    else
    {
    temp->link=(struct poly*)malloc(sizeof(struct poly));
    temp=temp->link;
    printf("Enter Coefficient and exponent for Node %d\n",z);
    scanf("%d %d",&temp->coff,&temp->expo);
    }
    z++;
    printf("Do you want to create another node\n");
    fflush(stdin);
    scanf("%c",&c);
    if(c!='y')
    {
    temp->link=NULL;
    break;
    }
    }
    // TARVERSING
    n1=start;
    printf("Traversal\n");
    while(n1!=NULL)
    {
    printf(" %2dx^%d + ",n1->coff ,n1->expo);
    n1=n1->link;
    }
    printf("\b\b\nTHE END\n");
    getch();
    }

    ReplyDelete