链表的简单介绍:
链表是为了解决数组的局限。
把数组看成一个大小确定的容器。则它的问题就是大小是确定的。而且必须在开辟内存空间之前,就确定好数组的大小。比如,num[10]. 这样就经常会出现,空间不足或者浪费,因为大小不可以改变。
所以,我们需要更灵活的–链表。它是把一个大的容器,分割成无数小的容器,每个容器里面放上合适的元素,然后连接起来。
链表的特点:
1. 有一个头指针 head, 它是指向第一个链表元素的位置;
2. 然后,每一个链表都有一个next指针,它会指向下一个链表的位置;
- 静态链表:
结点的数据在内存中的分布是在编译时就确定好了的,不会在运行时再进行动态地分配空间,例如不能在程序运行时,动态地对各个结点进行创建,添加或者删除的工作,这都是在运行前就已经确立好了的,我们只能在编译前修改指向结点的指针。
一个简单的链表结构 book:
struct book
{
int num;
float price;
struct book *next;
};
下面看使用 结构体 和 类 分别来实现一个小的链表:
- 结构体 – struct
#include <iostream>
using namespace std;
const int NULL = 0;
struct book
{
int num; //图书编号
float price;
book *next; //指向下一个node
};
int main()
{
book x,y,z, *head, *p;
x.num = 10000; x.price = 14.5;
y.num = 10001; y.price = 23.4;
z.num = 10002; z.price = 25.0;
head = &x;
x.next = &y;
y.next = &z;
z.next = NULL;
p = head;
while(p != NULL)
{
cout << p->num <<endl<<p->price<<endl;
p = p->next;
}
return 0;
}
- 类的链表 class
#include <iostream>
using namespace std;
const int NULL = 0;
class book
{
public:
int num; //图书编号
float price;
book *next; //指向下一个node
};
int main()
{
book x,y,z, *head, *p;
x.num = 10000; x.price = 14.5;
y.num = 10001; y.price = 23.4;
z.num = 10002; z.price = 25.0;
head = &x;
x.next = &y;
y.next = &z;
z.next = NULL;
p = head;
while(p != NULL)
{
cout << p->num <<endl<<p->price<<endl;
p = p->next;
}
return 0;
}
动态链表:
建立一个动态的链表,就是程序运行时,根据用户的输入,从无到有, 依次建立起一个表格。这个表格中的数据都依次 保存在各个结点上,每个结点都是用new操作符来动态开辟,结点与结点之间用指针next相关联。
C语言中:
void *p = malloc(sizeof(struct book));
free(p);
C++语言中:
book *p = new book;
delete p;
说明:C用的是标准库函数,C++用的是操作符。一般多用new和delete;
一个小的例子:
建立一个小的图书管理表。
- 图书编号 num;
- 图书价格 price;
- p1 下一个结点的指针;
- p2 本结点的指针;
- head 做头结点;
- next 指向下一个结点;
#include <iostream>
#include <string>
using namespace std;
class book
{
public:
int num;
float price;
book *next;
};
book *head = NULL;
book *creat() //定义一个返回book类指针的create函数。
{
book *p1;
book *p2;
p1 = new book; //创建一个新的book类对象;
head = p1;
p2 = p1;
cout <<"请输入图书的编号,以0结束"<<endl;
cin>>p1->num;
if(p1->num != 0)
{
cout <<"请输入图书的价格"<<endl;
cin >> p1->price;
}
else
{
delete p1;
p2 = NULL;
head = NULL;
return head;
}
while(p1->num != 0)
{
p2 = p1;
p1 = new book;
cout <<"请输入图书的编号,以0结束"<<endl;
cin>>p1->num;
if(p1->num != 0)
{
cout <<"请输入图书的价格"<<endl;
cin >> p1-> price;
}
p2 -> next = p1;
}
delete p1;
p2 ->next = NULL;
return head;
}
int main()
{
create();
reutnr 0;
}
《未完待续》……