您的位置:首页 > 其它

创建一个链表、删除一个节点、插入一个节点--实验

2013-03-19 00:30 423 查看
创建一个链表、删除一个节点、插入一个节点:

(说明:在VC6.0能够正常运行,仅供参考)

#include <stdio.h>
#include <malloc.h>

int n=0;

void print_list(struct student *head);
struct student *creat();
struct student *del(struct student *head,int num);
struct student *insert(struct student *head,struct student *p);

struct student
{
int num;
float score;
struct student *next;
};

int main()
{
int number;
struct student *head,stu;
head = NULL;

head = creat();
print_list(head);

printf("please input the del number:\n");
scanf("%d",&number);
head = del(head,number);
print_list(head);

printf("please input the insert number:\n");
scanf("%d,%f",&stu.num,&stu.score);
head = insert(head,&stu);
print_list(head);

return 0;
}

/*************创建一个节点********************/
struct student *creat(void)
{
struct student *head,*tail,*p;
head = tail = p = NULL;
tail = p = (struct student *)malloc(sizeof(struct student));
printf("please input the number:\n");
scanf("%d,%f",&p->num,&p->score);
while (p->num != 0)
{
n = n+1;
if (n == 1)
{
head = p;
}
else
{
tail->next = p;
tail = p;
}

p = malloc(sizeof(struct student));
scanf("%d,%f",&p->num,&p->score);
}
tail->next = NULL;
return (head);
}

/***************删除一个节点*****************/
struct student *del(struct student *head,int num)
{
struct student *p1,*p2;
p1 = p2 = NULL;
p1 = head;
while (p1->num != num && p1->next != NULL)
{
p2 = p1;
p1 = p1->next;
}
if (num == p1->num)
{
if (p1 == head)
{
head = p1->next;
}
else
{
p2->next = p1->next;
}
printf("del the number:%d\n",num);
}
return (head);
}

/************插入一个节点**************/
struct student *insert(struct student *head,struct student *p)
{
struct student *p0,*p1,*p2;
p1 = head;
p0 = p;
if (head == NULL)
{
head = p0;
p0->next = NULL;
}
else
{
while ((p0->num > p1->num)&&(p1->next != NULL))
{
p2 = p1;
p1 = p1->next;
}
if (p0->num <= p1->num)
{
if (head == p1)
{
head = p0;
}
else
{
p2->next = p0;
p0->next = p1;
}
}
}

return (head);
}

void print_list(struct student *head)
{
struct student *p;
printf("now,these %d records are:\n",n);
p = head;
if (head != NULL)
{
do
{
printf("%d,%f\n",p->num,p->score);
p = p->next;
} while (p != NULL);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐