所谓动态链表是指在程序执行过程中从无到有地建立起一个链表,既一个一个地开辟结点和输入各结点的数据,并建立起前后相连的关系。
例题:
#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;
head=&a;
a.next=&b;
b.next=&c;
c.next=NULL;
p=head;
do
return 0;
}
1.针对例子写一个函数creat,用来建立一个动态链表。各结点的数据由键盘输入。
#include <iostream>
using namespace std;
#define NULL0
struct student
{long num;
float score;
student *next;
};
student*creat(void)
{student *head;
student *p1,*p2;
int n=0;
p1=p2=newstudent;
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
}while(p!=NULL);
}
3.写一个函数del,用来删除动态链表中的一个指定的结点(由实参指定某一学号,表示要删除该学生结点)。
#include <iostream>
using namespace std;
#define NULL0
struct student
{long num;
float score;
student *next;
};
intn;