-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLinkedList.cpp
More file actions
100 lines (97 loc) · 1.95 KB
/
LinkedList.cpp
File metadata and controls
100 lines (97 loc) · 1.95 KB
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
#include <iostream>
using namespace std;
class Node {
public:
int data;
Node* next;
Node()
{
data = 0;
next = NULL;
}
Node(int data)
{
this->data = data;
this->next = NULL;
}
};
class Linkedlist {
Node* head;
public:
Linkedlist() { head = NULL; }
void insertNode(int);
void printList();
void deleteNode(int);
};
void Linkedlist::deleteNode(int nodeOffset)
{
Node *temp1 = head, *temp2 = NULL;
int ListLen = 0;
if (head == NULL) {
cout << "List empty." << endl;
return;
}
while (temp1 != NULL) {
temp1 = temp1->next;
ListLen++;
}
if (ListLen < nodeOffset) {
cout << "Index out of range"
<< endl;
return;
}
temp1 = head;
if (nodeOffset == 1) {
head = head->next;
delete temp1;
return;
}
while (nodeOffset-- > 1) {
temp2 = temp1;
temp1 = temp1->next;
}
temp2->next = temp1->next;
delete temp1;
}
void Linkedlist::insertNode(int data)
{
Node* newNode = new Node(data);
// Assign to head
if (head == NULL) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
void Linkedlist::printList()
{
Node* temp = head;
if (head == NULL) {
cout << "List empty" << endl;
return;
}
while (temp != NULL) {
cout << temp->data << " ";
temp = temp->next;
}
}
int main()
{
Linkedlist list;
list.insertNode(1);
list.insertNode(2);
list.insertNode(3);
list.insertNode(4);
cout << "Elements of the list are: ";
list.printList();
cout << endl;
list.deleteNode(2);
cout << "Elements of the list are: ";
list.printList();
cout << endl;
return 0;
}