动态建立链表

所谓动态链表是指在程序执行过程中从无到有地建立起一个链表,既一个一个地开辟结点和输入各结点的数据,并建立起前后相连的关系。

例题:
#include <iostream>
using namespace std;
#define NULL0    
struct student
{long num;
float score;
struct student *next;
};
int main()
{student a,b,c,*head,*p;
a.num=10001; a.score=89.5;
b.num=10003; b.score=90;
c.num=10007;c.score=85;    //为结点的num和score成员赋值
head=&a;                     //将结点a的起始地址赋给头指针head
a.next=&b;                   //将结点b的起始地址赋给a结点的next成员
b.next=&c;                   //将结点c的起始地址赋给b结点的next成员
c.next=NULL;                 //c结点的next成员不存放其他结点地址
p=head;                      //使p指针指向a结点
do       
  {cout<<p->num<<""<<p->score<<endl;//输出p指向的结点的数据
   p=p->next;                               //使p指向下一结点
  }while(p!=NULL);                         //输出完c结点后p的值为NULL
return 0;
}

1.针对例子写一个函数creat,用来建立一个动态链表。各结点的数据由键盘输入。


#include <iostream>
using namespace std;
#define NULL0    
struct student
{long num;
float score;
student *next;
};   
                   //定义n为全局变量,本文件模块中各函数均可使用它
student*creat(void)    //定义函数。此函数带回一个指向链表头的指针
{student *head;
student *p1,*p2;
int n=0;
p1=p2=newstudent;      //开辟一个新单元,并使p1,p2指向它
cin>>p1->num>>p1->score;
head=NULL;
while(p1->num!=0)
{n=n+1;
if(n==1) head=p1;
else p2->next=p1;
p2=p1;
p1=new student;
cin>>p1->num>>p1->score;
}
p2->next=NULL;
return(head);
}


2.写一个函数print,将上题建立的链表中各结点的数据依次输出。


#include <iostream>
using namespace std;
#define NULL0    
struct student
{long num;
float score;
student *next;
};   
intn;                   
void print(student *head)
{student *p;
cout<<"Now,These"<<n<<"records are:"<<endl;
p=head;
if(head!=NULL)
do
   {cout<<p->num<<""<<p->score<<endl;
    p=p->next;
}while(p!=NULL);
}


3.写一个函数del,用来删除动态链表中的一个指定的结点(由实参指定某一学号,表示要删除该学生结点)。


#include <iostream>
using namespace std;
#define NULL0    
struct student
{long num;
float score;
student *next;
};   
intn;    <

  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值