程序设计与问题求解实验报告六
——结构体与链表程序设计
文章目录
前言
提示:以下是本篇文章正文内容,下面案例可供参考
一、实验目的
1.掌握结构化数据的编程使用;
2.掌握指针与内存地址的关系;
3.掌握通过指针动态申请和释放内存的编程方法;
4.掌握单向链表的基本操作。
二、实验内容和步骤
1.修改错误程序——结构体相关编程
程序实现输出图书的名字和单价,错误代码如下:
#include <stdio.h>
struct book
{
float price;//价格
char name[10];//名字
}
int main(void)
{
struct book myBook;
myBook={5.6,"the world is flat"};
printf("book name=%s,book price=%f",myBook.name,myBook.price);
return 0;
}
修改后:
错误原因分析:结构体中的name字符串长度不够,结构体末尾没有‘;’ ,结构体初始化方式错误。
2.修改错误程序——链表相关编程
输入若干学生的信息(学号、姓名、成绩),当输入学号为 0 时结束,用单向链表组织这些学生信息后,再按序输出。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
structstud_node
{
intnum;
char name[20];
int score;
structstud_node *next;
};
int main()
{
structstud_node *head,*tail,*p;
intnum,score;
char name[20];
int size = sizeof(structstud_node);
head=tail=NULL;
printf(“input num,name and score:\n”);
scanf(“%d”,&num);
while(num != 0)
{
p=malloc(size);
scanf(“%s%d”,name,&score);
p->num=num;
strcpy(p->name,name);
p->score=score;
p->next=NULL;
tail->next=p;
tail=p;
scanf(“%d”,&num);
}
for(p=head;p->next != NULL;p=p->next)
printf(“%d %s %d\n”,p->num,p->name,p->score);
return 0;
}
修改后:
测验一下:
3.简单有序链表的创建和查询修改
(假设链表的第一个有数据的节点编号为1)
(1)建立一个单链表 21 3 15 27 11 18,并输出该链表;
(2)输入序号n,查找序号为n的结点,并输出;
(3)输入值x,查找值为x的结点,并输出;
(4)插入结点: 输入序号 n和值x。在序号为n的结点后插入x,并输出该链表;
(5)删除结点: 输入序号 n,删除序号为 n 的结点,并输出该链表。
实现代码:
测验一下:
三、实验总结
这两次的实验对我来说比较困难,上一次的磕磕绊绊的完成了,这一次由于对链表的创建理解的不是很好,导致对它的运用出现了很多问题,花了非常多的时间去查询、了解一些有关的资料,同时通过问同学、上网查询等方法最终完成了实验。这次的实验使我了解了链表,深入了解了对链表的快速插入删除元素优点。但是,我对这些仍然不够熟练,容易犯迷糊,仍需多加练习。