-
Notifications
You must be signed in to change notification settings - Fork 195
/
add_node_as_head_in_LL.cpp
76 lines (57 loc) · 1.19 KB
/
add_node_as_head_in_LL.cpp
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
#include<stdio.h>
#include<stdlib.h>
typedef struct node
{
int data;
struct node *next;
}node;
node* insertNodeAsHeadNode(int head_value , node* head)
{
node* p;
p=(node*)malloc(sizeof(node));
p->data = head_value;
p->next = NULL;
p->next = head;
head = p;
return head;
}
int main()
{
int a , i = 1 , n ,r , head_value; // i = 0 is also ok....
node *p,*q,*start;
printf("Enter the number of nodes");
scanf("%d",&n);
printf("Enter node %d \n",i); // you can also start with i = 0
p = (node*)malloc(sizeof(node));
scanf("%d",&a);
p->data = a;
p->next = NULL;
start = p;
for(i=2;i<=n;i++) //if i=0 , then for ( i = 1; i < n; i++ )
{
printf("Enter node %d \n",i);
q = (node*)malloc(sizeof(node));
scanf("%d",&a);
q->data = a;
q->next = NULL;
p->next = q;
p = p->next;
}
p = start;
while(p!=NULL)
{
printf("\t %d", p->data);
p = p->next;
}
printf("\n \n Enter the value which you want to include as head node");
scanf("%d",&head_value);
start = insertNodeAsHeadNode(head_value , start);
printf("\n");
p = start;
while(p!=NULL)
{
printf("\t %d",p->data);
p = p->next;
}
return 0;
}