forked from sunidhi2001/Hacktoberfest2022-accepted
-
Notifications
You must be signed in to change notification settings - Fork 0
/
InsertLinkedList.cpp
104 lines (83 loc) · 1.45 KB
/
InsertLinkedList.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
#include <iostream>
using namespace std;
struct node
{
int data;
struct node *next;
};
struct node *head = NULL;
void insert_at_beg(int);
void create_list(int);
void traverse();
int main()
{
create_list(10);
create_list(20);
create_list(30);
cout << "list before insert function :" << endl;
traverse();
cout << "\n\n";
// inserting two nodes in the list
insert_at_beg(1);
insert_at_beg(2);
cout << "list after insert function :" << endl;
traverse();
cout << endl;
return 0;
}
void create_list(int x)
{
struct node *new_node, *temp;
temp = head;
new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = x;
new_node->next = NULL;
if (head == NULL)
{
head = new_node;
head->next = NULL;
}
else
{
while (temp->next != NULL)
{
temp = temp->next;
}
temp->next = new_node;
}
}
void insert_at_beg(int x)
{
struct node *new_node;
new_node = (struct node *)malloc(sizeof(struct node));
new_node->data = x;
new_node->next = NULL;
if (head == NULL)
{
head = new_node;
return;
}
else
{
new_node->next = head;
head = new_node;
}
}
void traverse()
{
struct node *temp;
temp = head;
if (temp == NULL)
{
cout << "Linked list is empty" << endl;
return;
}
// while(temp != NULL)
while (temp->next != NULL)
{
cout << temp->data << " -> ";
temp = temp->next;
}
// Print last node
cout << temp->data << "-> NULL";
}