-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmy_linked_list.cpp
executable file
·118 lines (108 loc) · 2.38 KB
/
my_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
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
#include <bits/stdc++.h>
using namespace std;
class Node
{
public:
int data;
Node *next;
Node(int data)
{
this->data = data;
next = NULL;
}
};
class LinkedList
{
public:
Node *head;
LinkedList(int arr[], int size)
{
head = new Node(arr[0]);
Node *tail = head;
int i = 1;
while (i < size)
{
Node *newNode = new Node(arr[i]);
tail->next = newNode;
tail = newNode;
i++;
}
}
int countNode()
{
Node *temp = head;
int length = 0;
while (temp != NULL)
{
length++;
temp = temp->next;
}
return length;
}
Node *nodeAt(int index)
{
Node *temp = head;
int i = 0;
while (i < index)
{
temp = temp->next;
i++;
}
return temp;
}
void print()
{
Node *temp = head;
while (temp != NULL)
{
cout << temp->data << " ";
temp = temp->next;
}
cout << endl;
}
void insertAt(int data, int index)
{
Node *newNode = new Node(data);
if (index == 0)
{
newNode->next = head;
head = newNode;
}
else
{
Node *prevNode = nodeAt(index - 1);
Node *nextNode = prevNode->next;
prevNode->next = newNode;
newNode->next = nextNode;
}
}
void removeNodeAt(int index)
{
if (index == 0)
{
head = head->next;
}
else
{
Node *prevNode = nodeAt(index - 1);
Node *nextNode = prevNode->next->next;
prevNode->next = nextNode;
}
}
};
int main()
{
int arr[] = {1, 4, 5, 100, 8, 60};
int length = sizeof(arr) / sizeof(arr[0]);
LinkedList mylist(arr, length);
// cout<<"Before Remove:"<<endl;
cout<<"Length: "<<mylist.countNode()<<endl;
mylist.print();
// cout<<"After Remove:"<<endl;
// mylist.removeNodeAt(5);
mylist.insertAt(200, 6);
cout<<"After insertion Length: "<<mylist.countNode()<<endl;
mylist.print();
// cout<<"Data: "<<mylist.nodeAt(2)->data<<endl;
return 0;
}