c++语言之前有学过一些,很久时间没用语法忘得差不多了,我准备重拾c++,,尽管现在还带有不少c的风格,但写博客是为了备忘,也给日后的学习做一个参考,以链表为例,运用c++中的构造函数对链表进行初始化,析构函数来销毁链表,特别是在对象很多的时候,比如要定义多个链表对象,c++相比c就有了很大优越性。
#include<iostream>
using namespace std;
typedef int DATA;
struct LNode{//结点类
DATA data;
LNode *next;
};
struct List{//链表类
LNode *head; //头指针
List()
{//构造函数
head = NULL; //空链表
}
~List()
{//析构函数
LNode* p = head,*p1;
while(p)
{
p1 = p;
p = p->next;
delete p;
}
cout << "链表已销毁" << endl;
}
void AddNode(int d)
{//添加结点
LNode *p = new LNode;
p->data = d;
p->next = head; //头插法
head = p;
}
void print()
{//遍历输出链表
LNode *p = head;
while(p)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
int GetCount()
{
LNode *p = head;
int i = 0;
while(p)
{
++i;
p = p->next;
}
return i;
}
};
int main()
{
List l1,l2; //定义两个链表对象,系统已自动调用构造函数将其初始化
int i;
for(i=0; i<10; i++)
{
l1.AddNode(i);
}
for(i=10; i<20; i++)
{
l2.AddNode(i);
}
cout << "list1: ";
l1.print();
cout << "list2: ";
l2.print();
cout << "list1-Length = " << l1.GetCount() << endl;
cout << "list2-Length = " << l2.GetCount() << endl;
return 0; //结束时系统自动调用析构函数将两链表对象销毁
}