Doubly list

DOUBLY LINKED LIST

1.   Design a doubly linked list to represent sparse matrix. Each node in the list can have the row and column index of the matrix element and the value of the element

//Program starts here
#include<stdio.h>
#include<stdlib.h>
struct node{
     int data;
     int row,col;
     struct node *next;
     struct node *prev;
};
typedef struct node snode;
snode *f=NULL,*l=NULL,*p,*new;
snode *l1=NULL;
snode *insert(snode *f,int x,int r, int c)
{
     new=malloc(sizeof(snode));
     new->data=x;
     new->col=c;
     new->row=r;
     new->next=new->prev=NULL;
     if(f==NULL)
     {
          f=new;
     }
     else
     {
          p=f;
          while(p->next!=NULL)
              p=p->next;
          p->next=new;
          new->prev=p;
     }
     return f;
}
int main()
{
     snode *tmp;
     int data,i,j,r,c,flag;
     int r1,c1;
     printf("matrix row and column\n");
     scanf("%d",&r);
     scanf("%d",&c);
     printf("enter mattrix data\n");
     for(i=0;i<r;i++)
     {
          for(j=0;j<c;j++)
          {
              r1=i+1;
              c1=j+1;
              printf(" \nrow %d  and  column %d :\n",r1,c1);
              scanf("%d",&data);
              if(data!=0)
                   l1=insert(l1,data,i,j);
          }
     }


     for(i=0;i<r;i++)
     {
          for(j=0;j<c;j++)
          {
              tmp=l1;
              flag=0;
              while(tmp!=NULL)
              {
                   if((tmp->row==i) && (tmp->col==j))
                   {
                        printf("%d\t",tmp->data);
                        flag=1;
                        break;
                   }
                   tmp=tmp->next;
              }
              if(flag!=1)
              {
                   printf("%d\t",0);
              }
          }
          printf("\n");
     }
}


No comments:

Post a Comment