DEV Community

Adarsh
Adarsh

Posted on

Inserting code at the begenning of the linked list

#include <stdlib.h>
#include <stdio.h>

struct Node
{
  int data;
  struct Node *next;
};
// struct Node *head;

Node *insertVal(Node *head, int data)
{
  Node *temp = (Node *)malloc(sizeof(struct Node));
  temp->data = data;
  temp->next = head;
  head = temp;
  return head;
};
void printData(Node *head)
{
  struct Node *temp = head;
  printf("List is : ");
  while (temp != NULL)
  {
    printf("%d ", temp->data);
    temp = temp->next;
  }
  printf("\n");
};
int main()
{
  Node *head = NULL;
  printf("How many numbers ? \n");
  int n, x, i;
  scanf("%d", &n);
  printf("The number that u have entered is %d", n);
  for (i = 0; i < n; i++)
  {
    printf("Enter the data for the list \n");
    scanf("%d", &x);
    head = insertVal(head, x);
    printData(head);
  }
  return 0;
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)