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
| template <typename E> class Link{
public:
E element;
Link *next;
Link(const E& elemval, Link *nextval = NULL){
element = elemval;
next = nextval;
}
Link(Link *nextval = NULL){
next = nextval;
}
};
template <typename E> class LList: public List<E>{
private:
Link<E> *head;
Link<E> *tail;
Link<E> *curr;
int count;
void init(){
curr = tail = head = new Link<E>;
count = 0;
}
void removeall(){
while(head != NULL){
curr = head;
head = head -> next;
delete curr;
}
}
public:
LList(int size=100){
init();
}
~LList(){
removeall();
}
void clear(){
removeall();
init();
}
void insert(const E& it){
//给要增加的节点初始化
curr -> next = new Link<E>(it, curr -> next);
//如果要curr指针就是再末尾
//那么把curr的下一个赋给tail
if(tail == curr)
tail = curr -> next;
count++;
}
void append(const E& it){
//直接把末尾指针的next指向新建的link
tail = tail -> next = new Link<E>(it, NULL);
count++;
}
//注意,这里要删除的节点叫做curr->next
E remove(){
//先把要删除的node的值存起来
E it = curr -> next -> element;
//用temp存一下要删除的节点
Link<E> *temp = curr -> next;
//如果这个要删除的点是末尾,那么把末尾前一个节点赋给tail
if(tail == curr -> next)
tail = curr;
//否则,把要删除的节点的前一个节点的next指向要删除节点的下一个
curr -> next = curr -> next -> next;
delete temp;
count--;
return it;
}
void moveToStart(){
curr = head;
}
void moveToEnd(){
curr = tail;
}
void prev(){
if(curr == head)
return ;
Link<E> *temp = head;
//向左移动一个单位
//做法是先用temp存一个head,然后向右找,直到找到curr的前一个,然后把curr的前一个赋给curr
while(temp -> next != curr)
temp = temp -> next;
curr = temp;
}
void next(){
//只要curr指针不是tail,那么就向后移动
if(curr != tail)
curr = curr -> next;
}
int length(){
return count;
}
int currPos() const{
Link<E> *temp = head;
//用temp指针存head,然后依次向后遍历,并且每次后移count+1
int i;
for(i = 0; i < count; i++){
temp = temp -> next;
}
return i;
}
void moveToPos(int pos){
curr = head;
//先把current的指针指向head
//然后一直向后移动,直到pos次
for(int i = 0; i < pos; i++){
curr = curr -> next;
}
}
const E& getValue() const{
return curr -> next -> element;
}
};
|