C语言习题 链表建立,插入,删除,输出

Problem B: C语言习题 链表建立,插入,删除,输出

Time Limit: 1 Sec  Memory Limit: 128 MB
Submit: 222  Solved: 92
[Submit][Status][Web Board]

Description

编写一个函数creatlink,用来建立一个动态链表。(包含学号和成绩)
编写一个函数printlink,用来输出一个链表。
编写一个函数dellink,用来删除动态链表中一个指定的结点(由实参指定某一学号,表示要删除该学生结点)。
编写一个函数insertlink,用来向动态链表插入一个结点。
编写一个函数freelink,用来释放一个动态链表。

Input

输入多个学生的学号和成绩,建立动态链表,以0 0 结束
输入学号,删除链表中的对应结点
插入两个链表结点

Output

输出的链表

#include<iostream>
#include<iomanip>
using namespace std;
struct student
{int num;
double score;
student *p;
};

student *creatlink(void)
{
	student *head,*p,*s;
	head=new student;
	s=p=head;
	while(1)
	{cin>>(*p).num>>(*p).score;
	if((*p).num==0&&(*p).score==0)
	{delete p;(*s).p=NULL; return head;}
	(*p).p=new student;
	s=p;
	p=p->p;
	(*p).p=NULL;
	}
	
	}
student *dellink(student *head,long a)
{student *p,*h;
h=p=head;
if((*p).num==a)
{head=(*p).p;
delete p;   //////////////////////////
return head;}
while(1)
{
	if((*p).num==a)
{h->p=p->p;delete p;return head;}
h=p;
p=(*p).p;
}
return head;}
student *insertlink(student *head,student *a)
{student *p,*h,*s;
s=h=head;
p=new student ;
p->num=a->num;
p->score=a->score;
p->p=NULL;
if(p->num<head->num)
{head=p;
p->p=h;return head;}
while(1)
{if(h->num>p->num)
{
p->p=h;
s->p=p;return head;}
s=h;
h=h->p;
if(h==NULL)
{s->p=p;p->p=NULL;return head;}
}
}
void printlink(student *head)
{  
while(head!=NULL)
{  
	cout<<head->num<<' ';

    cout<<setiosflags(ios::fixed)<<setprecision(2)<<head->score<<endl;;
	head=head->p;

}
}


    void freelink(student *head)
	{
		 student *p;
		 while(head!=NULL)
		 {
			 p=head->p;
			 delete head;
			 head=p;
		 
		 }
	
	}
int main()

{

    student *creatlink(void);

    student *dellink(student *,long);

    student *insertlink(student *,student *);

    void printlink(student *);

    void freelink(student *);

    student *head,stu;

    long del_num;

    head=creatlink();

    cin>>del_num;

    head=dellink(head,del_num);

    cin>>stu.num>>stu.score;

    head=insertlink(head,&stu);

    cin>>stu.num>>stu.score;

    head=insertlink(head,&stu);

    cout<<setiosflags(ios::fixed);

    cout<<setprecision(2);

    printlink(head);

    freelink(head);

    return 0;

}


 

posted @ 2014-03-24 11:56  IT专业户  阅读(286)  评论(0编辑  收藏  举报