-
Notifications
You must be signed in to change notification settings - Fork 0
/
33.1.1_Singly-Linked-List-Insertion-Using-Loops.cpp
112 lines (100 loc) · 2.36 KB
/
33.1.1_Singly-Linked-List-Insertion-Using-Loops.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
//* Insertion using loops in Linked List.
// todo Visualization link:- https://excalidraw.com/#json=H7C2SbYLRuD4kcviuvvWn,WeYkH-Bt_RkHf60KrqB29A
#include <iostream>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int value)
{
data = value;
next = NULL;
}
};
// Print the value.
void printLL(Node *Head)
{
Node *temp = Head;
// while (temp != NULL)
while (temp)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
int main()
{
system("clear");
//* Static way.
// Node A1(4);
//* Dynamic Way.
Node *Head;
// Head = new Node(4);
// cout << Head->data << endl;
// cout << Head->next << endl;
Head = NULL;
int arr[] = {2, 4, 6, 8, 10};
// Insert the Node at Beginning. Tc:- O(n), Total SC:- O(n), Auxilary SC:- O(1).
// Linked list doesn't exist.
// for (int i = 0; i < 5; i++)
// {
// if (Head == NULL)
// {
// Head = new Node(arr[i]);
// }
// // Linked list exists.
// else
// {
// Node *temp;
// temp = new Node(arr[i]);
// temp->next = Head;
// Head = temp;
// }
// }
// // Print the value.
// printLL(Head);
// Insert the node at the end. TC:- O(n^2), Total SC:- O(n), Auxilary SC:- O(1).
// Linked list is not exist.
// for (int i = 0; i < 5; i++)
// {
// if (Head == NULL)
// {
// Head = new Node(arr[i]);
// }
// // Linked list exists.
// else
// {
// Node *tail = Head;
// while (tail->next != NULL)
// {
// tail = tail->next;
// }
// // Node *insert;
// // insert = new Node(-1);
// // tail->next = insert;
// tail->next = new Node(arr[i]);
// }
// }
// Insert the node at the end. TC:- O(n), Total SC:- O(n), Auxilary SC:- O(1).
Node *tail = NULL;
for (int i = 0; i < 5; i++)
{
if (Head == NULL)
{
Head = new Node(arr[i]);
tail = Head;
}
// Linked list exists.
else
{
tail->next = new Node(arr[i]);
tail = tail->next;
}
}
// Print the value.
printLL(Head);
return 0;
}