-
Notifications
You must be signed in to change notification settings - Fork 0
/
Insertion_at_beginning_Linked_List.cpp
78 lines (65 loc) · 1.28 KB
/
Insertion_at_beginning_Linked_List.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
77
78
#include <iostream>
using namespace std;
struct node
{
int data;
node * next;
} *head, *ptr, *newptr, *temp;
node * create_new_node(int k)
{
ptr = new node;
ptr -> data = k;
ptr -> next = NULL;
return ptr;
}
void insert_at_beginning(node * np)
{
if (head == NULL)
{
head = np;
}
else
{
temp = head;
np -> next = temp;
head = np;
}
}
void display(node * np)
{
while (np != NULL)
{
cout << np -> data << " --> ";
np = np -> next;
}
cout << "!!!\n";
}
int main()
{
head = NULL;
int info;
char ch = 'y';
while (ch == 'y' || ch == 'Y')
{
cout << "\n Enter the data for new node : ";
cin >> info;
cout << "Creating new node ! ";
newptr = create_new_node(info);
if (newptr != NULL)
{
cout << "Node created successfully ! ";
}
else
{
cout << "Cannot create node !";
exit(1);
}
cout << "Now inserting node at beginning ! ";
insert_at_beginning(newptr);
cout << "Now the linked list is : ";
display(head);
cout << "Press Y to enter more nodes at beginning else N to exit : ";
cin >> ch;
}
return 0;
}