1 struct Node {
2 int data;
3 Node* next;
4 Node(int d, Node* n = NULL)
5 : data(d),next(n) {
6
7 }
8 };
9
10 class List {
11 public:
12 List();
13 ~List();
14 void clear();
15 bool empty() const;
16 void push_back(const int& value);
17 void pop_back();
18 void insert(Node* pos, const int& value);
19 void remove(Node* pos);
20 int size() const {return count;}
21 Node* begin() const {return head;}
22 Node* end() const {return NULL;}
23 Node* getHead() const {return head;}
24 private:
25 int count;
26 Node* head;
27 };
28
29 List::List() : count(0), head(NULL) {}
30
31 List::~List() {
32 clear();
33 }
34
35 void List::clear() {
36 Node *p = head;
37 while (p != NULL) {
38 Node* hold = p;
39 p = p->next;
40 hold->next = NULL;
41 delete hold;
42 count--;
43 }
44 head = NULL;
45 }
46
47 bool List::empty() const {
48 return (count == 0);
49 }
50
51 void List::push_back(const int& value) {
52 Node *node = new Node(value);
53 if (empty()) {
54 node->next = head;
55 head = node;
56 } else {
57 Node *p = head;
58 while (p->next != NULL) {
59 p = p->next;
60 }
61 p->next = node;
62 }
63 count++;
64 }
65
66 void List::pop_back() {
67 if (count == 1) {
68 delete head;
69 head = NULL;
70 count--;
71 }
72 if (!empty()) {
73 Node *p = head, *pre;
74 while (p->next != NULL) {
75 pre = p;
76 p = p->next;
77 }
78 pre->next = NULL;
79 delete p;
80 count--;
81 }
82 }
83
84 void List::insert(Node* pos, const int& value) {
85 if (pos == head) {
86 Node *node = new Node(value);
87 node->next = head;
88 head = node;
89 count++;
90 } else {
91 Node *p = head;
92 while (p != NULL && p->next != pos) {
93 p = p->next;
94 }
95 if (p != NULL) {
96 Node *node = new Node(value);
97 node->next = pos;
98 p->next = node;
99 count++;
100 }
101 }
102 }
103
104 void List::remove(Node* pos) {
105 // 首先要判断链表是否为空
106 if (pos == NULL || empty())
107 return;
108 if (pos == head) {
109 head = head->next;
110 pos->next = NULL;
111 delete pos;
112 count--;
113 } else {
114 Node *p = head;
115 while (p != NULL && p->next != pos) {
116 p = p->next;
117 }
118 if (p != NULL) {
119 p->next = pos->next;
120 pos->next = NULL;
121 delete pos;
122 count--;
123 }
124 }
125 }