Storing numbers in link list

Problem statement
Write a c program to store values using link list, your program should store the values in order they are entered and the print the values. total number of inputs will be given by user,
for example
total number of integer you will enter 5
1
2
3
5
1
then your program should print
1
2
3
5
1
and store in the same manner only, i.e. the number which will be entered in the list will be in the last of the list

#include<stdio.h>
#include<stdlib.h>
struct node{
  int data;
  struct node * next;
};
struct node* scan(int n);
void print(struct node *head);
void add(struct node* head,int toadd);
int main()
{
  struct node *head;
  int n;
  head=NULL;
  printf("enter number of elements in the link list ");
  scanf("%d",&n);
  head=scan(n);
  printf("the elements entered by you is ");
  print(head->next);
  return 0;
}
void print(struct node *head)
{
  while(head!=NULL)
    {
      printf("%d ",head->data);
      head=head->next;
    }
  return;
}
struct node* scan(int n)
{
  int i,temp;
  struct node *head;
  head=(struct node *)malloc(sizeof(struct node));
  head->next=NULL;
  head->data=0;
  for(i=0;i<n;i++)
    {
      scanf("%d",&temp);
      add(head,temp);
    }
  return head;
}
void add(struct node* head,int toadd)
{
  struct node *newnode;
  while(head->next!=NULL)
    {
      head=head->next;
    }
  newnode=(struct node *)malloc(sizeof(struct node));
  newnode->data=toadd;
  head->next=newnode;
  newnode->next=NULL;
  return ;
}

No comments:

Post a Comment