zoukankan      html  css  js  c++  java
  • 动态链表的建立

    建立一个动态链表就是在程序执行时根据用户的输入从无到有一次建立起一个表格,这个表格中的数据都一次保存在各个节点上,每个节点都是用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 }

    结果演示

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

  • 相关阅读:
    字符串指针与字符数组的区别
    为什么stc15的单片机,运行了几秒后就蹦了
    判断一个数是否是2的整数次幂
    Ubuntu下使用gcc编译c文件,未识别cos,sin
    数字图像基本处理算法
    开发板启动时,内核打印出"can't access tty,job control turned off"
    c语言里如何调用汇编里的变量?
    leetcode516 Longest Palindromic Subsequence
    leetcode523 Continuous Subarray Sum
    leetcode650 2 Keys Keyboard
  • 原文地址:https://www.cnblogs.com/table/p/4732895.html
Copyright © 2011-2022 走看看