-
Notifications
You must be signed in to change notification settings - Fork 89
/
Copy pathDesign Linked Lists.cpp
115 lines (103 loc) · 2.37 KB
/
Design Linked Lists.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
class Node{
public:
int val;
Node *next;
Node (){
next=NULL;
}
};
class MyLinkedList {
public:
int siz;
Node *head;
MyLinkedList() {
head = NULL;
siz = 0;
}
int get(int index) {
if(index<siz){
Node *temp = head;
for(int i=0; i<index; i++){
temp = temp->next;
}
int ret = temp->val;
return ret;
}
else
return -1;
}
void addAtHead(int value) {
Node *first;
first = new Node;
first->val = value;
if(head!=NULL)
first->next = head;
head = first;
siz++;
}
void addAtTail(int value) {
Node *temp = head;
Node *add;
add = new Node();
add->val = value;
add->next = NULL;
if(temp == NULL){
head = add;
}
else{
while(temp->next != NULL){
temp = temp->next;
}
temp->next = add;
}
siz++;
}
void addAtIndex(int index, int value) {
if(index<=siz){
Node *add;
add = new Node;
add->val = value;
if(index==0){
add->next = head;
head = add;
}
else{
Node *temp = head;
for(int i=0; i<index-1; i++){
temp = temp->next;
}
add->next = temp->next;
temp->next = add;
}
siz++;
}
}
void deleteAtIndex(int index) {
if(index<siz){
Node *temp = head;
if(index == 0){
head = head->next;
delete temp;
}
else{
for(int i=0; i<index-1; i++){
temp = temp->next;
}
Node *del;
del = temp->next;
temp->next = del->next;
delete del;
}
siz--;
}
}
};
/**
* Your MyLinkedList object will be instantiated and called as such:
* MyLinkedList* obj = new MyLinkedList();
* int param_1 = obj->get(index);
* obj->addAtHead(val);
* obj->addAtTail(val);
* obj->addAtIndex(index,val);
* obj->deleteAtIndex(index);
*/