-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path707. Design Linked List.cpp
102 lines (92 loc) · 2.26 KB
/
707. Design 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
#include <iostream>
using namespace std;
class Node{
public:
Node(): next(NULL){};
Node(int value): val(value), next(NULL){};
int val;
Node* next;
};
class MyLinkedList {
public:
friend class Node;
MyLinkedList() {
}
int get(int index) {
if(head == NULL) return -1;
if(index > total) return -1;
int count = 0;
cur = head;
while(cur->next != NULL){
if(count == index) return cur->val;
count++;
cur = cur->next;
}
return cur->val;
}
void addAtHead(int val) {
total++;
if(head == NULL) head = new Node(val);
else{
Node* temp = new Node(val);
temp->next = head;
head = temp;
}
}
void addAtTail(int val) {
total++;
if(head == NULL) head = new Node(val);
else{
Node* temp = new Node(val);
cur = head;
while(cur->next != NULL){
cur = cur->next;
}
cur->next = temp;
}
}
void addAtIndex(int index, int val) {
if(index > total+1) return; //遠超出來
total++;
if(index == 0){
Node* temp = new Node(val);
temp->next = head;
head = temp;
return;
}
int count = 0;
cur = head;
while(cur != NULL){
if(count == index-1){
Node* temp = new Node(val);
temp->next = cur->next;
cur->next = temp;
break;
}
count++;
cur = cur->next;
}
}
void deleteAtIndex(int index) {
if(index > total) return;
total--;
if(index == 0){
head = head->next;
return;
}
int count = 0;
cur = head;
while(cur->next != NULL){
if(count == index-1){
cur->next = cur->next->next;
break;
}
count++;
cur = cur->next;
}
}
private:
Node* head = NULL;
Node* cur = NULL;
int total = -1; //因為第一個算0
};