链表的类
大家看一下这个链表的类,为什么在构造函数中head = NULL,不是head -> next = NULL。如果用第二种的话会报错。head只是一个指针,它为空表示它内部成员指针 next也为空吗?
class LinkedList {
public:
struct Node {
int val;
Node* next;
Node(int v, Node* n) { val = v; next = n; }
};
private:
Node* head;
public:
LinkedList() {
head = NULL;
}
~LinkedList() {
Node* q;
for (Node* p = head; p != NULL; p=q) {
q=p->next;
delete[] p;
}
}
void addFirst(int v) {
Node* p = new Node(v, head);
p->val = v;
p->next = head;
head = p;
}
void addLast(int v) {
Node* p;
Node* q;
if (head == NULL) {
head = new Node(v, NULL);
return;
}
for (p = head; p != NULL; q=p, p = p->next){}
q->next = new Node(v, NULL);
}
void remove(Node* p) {
Node* q;
for (q = head; q != NULL; q=q->next)
if (q->next == p) {
q->next = p->next;
return;
}
}
Node* getFirst() {
return head;
}
Node* getLast() {
Node* p;
Node* q;
for (p = head; p != NULL; q=p, p = p->next);
return q;
}
};