Fork me on GitHub

动态链表的建立

建立一个动态链表就是在程序执行时根据用户的输入从无到有一次建立起一个表格,这个表格中的数据都一次保存在各个节点上,每个节点都是用new操作符来动态开辟,节点与节点之间用指针next相关联

代码示例

 1 #include <iostream>
 2 using namespace std;
 3 /*******************define class book************************/
 4 class book
 5 {
 6 public:
 7     int num;
 8     float price;
 9     book *next;            //the most important
10 };
11 
12 book *head=NULL;
13 /*********************creat() function**********************/
14 book *creat()
15 {
16     book *p1,*p2;
17     p1=new book;
18     head=p1;
19     p2=p1;
20     /***************the first time********************/
21     cout<<"请输入图书的编号,以0结束"<<endl;
22     cin>>p1->num;
23     if(p1->num!=0)
24     {
25         cout<<"请输入图书的价格"<<endl;
26         cin>>p1->price;
27     }
28     else
29     {
30         delete p1;p2=NULL;p2->next=NULL;head=NULL;return head;
31     }
32     /**********************again and again********************/
33     while(p1->num!=0)
34     {
35         p2=p1;        //p2 point to an old node
36         p1=new book;//p1 point to a new node
37         cout<<"请输入图书的编号,以0结束"<<endl;
38     cin>>p1->num;
39     if(p1->num!=0)
40     {
41         cout<<"请输入图书的价格"<<endl;
42         cin>>p1->price;
43     }
44     p2->next=p1;//the old node's next point to a new node,so it begin circulating
45     }
46     /*************************finish*************************/
47     delete p1;//delete new node while finishing cin;
48     p2->next=NULL;
49     return head;
50 }
51 /*************************main() function*****************************/
52 int main()
53 {
54     creat();
55     return 0;
56 }

 

结果演示

随即开始循环不断地建立动态链表

posted @ 2015-08-15 18:12  夏成都  阅读(1937)  评论(0编辑  收藏  举报