forked from codescoop/Play-with-Data-Structures
-
Notifications
You must be signed in to change notification settings - Fork 0
/
03_linked_list_insertion_1.cpp
127 lines (100 loc) · 2.66 KB
/
03_linked_list_insertion_1.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
/*
TOPIC: Linked List - Insertion-I
[Insertion at Head of Linked List]
we can create linked list using:
- Linked List Class (Object Oriented Programming)
- Function (Procedural Programming)
(functions to perform different operations in linked list)
Insertion in linked list can be done at:
- head
- middle
- tail
Why Dynamic Allocation not Static Allocation in Linked List ?
- In static allocation, when the function call is over, all the variables that are created statically
are destroyed.
Thus, the Node which we create inside the function will also get destroyed, when the function call is over.
Like: insertAtHead(head,3);
insertAtHead(head,99);
insertAtHead(head,10);
- So, to create chain of Nodes, we use dynamic memory allocation.
*/
#include <iostream>
using namespace std;
class Node{
public:
int data;
Node *next;
// constructor
Node(int d)
{
data = d;
next = NULL;
}
};
// Linked List Class (Object Oriented Programming)-----------------------------
/*
class LinkedList
{
Node *head;
Node *tail;
public:
LinkedList()
{
...
}
void insert(int d)
{
...
}
...
...
};
*/
// Functions (Procedural Programming)-----------------------------------------
// pass by value
// void insertAtHead(Node *headCopy, int d)
// pass a pointer by reference (because we want to make changes to the original head pointer)
void insertAtHead(Node *&head, int d)
{
if(head == NULL)
{
head = new Node(d);
return;
}
Node *n = new Node(d);
n->next = head;
head = n;
}
// pass by value (because we don't want to change the original head pointer)
void print(Node *head)
{
while(head != NULL)
{
cout << head->data << " -> ";
head = head->next;
}
cout << endl;
}
int main()
{
// since we don't have linked list class, we have to keep the track of head pointer
Node *head = NULL; // to store address of the first node
insertAtHead(head,3);
insertAtHead(head,99);
insertAtHead(head,10);
cout << "Linked List: ";
print(head);
print(head);
/* When using print() twice, Does data will be printed Twice or just Once ??
- As, print() function is taking parameter as "call by value". So, it will print data twice
But
- if print() function should have using "call by reference", then it will print data only once.
As, we have changed the original "head pointer" to NULL.
*/
return 0;
}
/*
OUTPUT:
Linked List: 10 -> 99 -> 3
10 -> 99 -> 3
*/