forked from swaaz/basicprograms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprogram.c
More file actions
93 lines (84 loc) · 2.05 KB
/
Copy pathprogram.c
File metadata and controls
93 lines (84 loc) · 2.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
/* Program to insert an element in the beginning of a linked list*/
#include <stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
}*head;
void createlist(int n);
struct node* insertNodeAtBeginning(int data,struct node* head);
void displaylist( );
int main()
{int n;
int data;
printf("Enter the value of n: ");
scanf("%d",&n);
createlist(n);
printf("Data in the list\n");
displaylist();
printf("Enter the data to insert at beginning: ");
scanf("%d",&data);
head= insertNodeAtBeginning(data,head);
displaylist();
return 0;
}
void createlist(int n)
{
struct node *temp,*newnode;
int data,i;
head=(struct node*)malloc(sizeof(struct node));
if(head==NULL)
{
printf("unable to locate memory");
}
printf("Enter data of first node1: ");
scanf("%d",&head->data);
head->next=NULL;
temp=head;
for(i=2;i<=n;i++)
{
newnode= (struct node *)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf("Unable to locate memory");
}
printf("Enter data of node %d: ",i);
scanf("%d",&data);
newnode->data=data;
newnode->next=NULL;
temp->next=newnode;
temp=temp->next;
}
}
struct node* insertNodeAtBeginning(int data,struct node* head)
{
struct node *newnode;
newnode=(struct node*)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf("Unable to allocate memory");
}
else
{
newnode->data=data;
newnode->next=head;
head=newnode;
printf("Data inserted successfully\n");
return head;
}
}
void displaylist()
{
struct node *temp;
if(head==NULL)
{
printf("list is empty");
}
temp=head;
while(temp!=0)
{
printf("data = %d\n",temp->data);
temp=temp->next;
}
}