但我感觉和结构差不多呀所以提前做了
怎么总是提醒类内连接指针没有声明;
类是把数据和方法封装起来.
[CODE] struct Node //链表的节点
{
int data;
Node *next;
};
//类声明
class List
{
private:
Node *head;
Node *tail;
public:
List();
~List();
void addToTail(int);
void deleteFromTail();
};
//类方法的定义
List::List() //构造
{
head = tail = 0;
}
List::~List() //析构
{
Node *p;
while(head != 0)
{
p = head->next;
delete head;
head = p;
}
}
void List::addToTail(int x) //增加到结尾
{
Node *tmp = new Node;
tmp->data = x;
tmp->next = 0;
if(tail != 0)
{
tail->next = tmp;
tail = tail->next;
}
else
head = tail = tmp;
}
void List::deleteFromTail() //从结尾删除
{
if(head == 0)
return;
else if(head == tail)
{
delete tail;
head = tail = 0;
}
else
{
Node *tmp = head;
while(tmp->next != tail)
tmp = tmp->next;
delete tail;
tail = tmp;
tail->next = 0;
}
}[/CODE]
可以在List中加入其他的需要的方法
使用时,如
List a; //定义了链表一个对象
a.addToTail(5); //a调用成员函数
a.deleteFromTail();