-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path设计链表
84 lines (78 loc) · 1.97 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
class MyLinkedList {
public:
MyLinkedList() { // 设置虚拟头结点会好做很多
list=new myLinkedList(0);
}
int get(int index) {
myLinkedList* cur=list->next;
int i=0;
while(cur!=NULL){
if(i==index){
i=cur->val;
return i;
}
i++;
cur=cur->next;
}
return -1;
}
void addAtHead(int val) {
myLinkedList* cur=new myLinkedList(val);
cur->next=list->next;
list->next=cur;
}
void addAtTail(int val) {
myLinkedList *cur=list;
while(cur->next!=NULL){
cur=cur->next;
}
cur->next=new myLinkedList(val);
}
void addAtIndex(int index, int val) {
myLinkedList *cur=new myLinkedList(0);
cur=list;
int i=0;
while(cur->next!=NULL){
if(i==index){
myLinkedList* tmp=new myLinkedList(val);
tmp->next=cur->next;
cur->next=tmp;
}
i++;
cur=cur->next;
}
if(cur->next==NULL&&i==index){
cur->next=new myLinkedList(val);
}
}
void deleteAtIndex(int index) {
myLinkedList *cur=new myLinkedList(0);
cur->next=list->next;
list=cur;
int i=0;
while(cur->next!=NULL){
if(i==index){
cur->next=cur->next->next;
break;
}
i++;
cur=cur->next;
}
}
private:
struct myLinkedList{
int val;
myLinkedList* next;
myLinkedList(int x) : val(x), next(NULL) {}
};
myLinkedList* list;
};
/**
* 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);
*/