macd八种形态图解:指针与链表
来源:百度文库 编辑:中财网 时间:2024/04/28 21:23:49
指针与链表
指针与链表
链表的创建、插入、删除函数程序
#include
#define PT "学号:%1d 姓名:%-10s 成绩:%6.1f\n",p->num,p->name,p->score
#define N sizeof(struct stud)
struct stud
{
long num;
char name[11];
long score;
struct stud *next;
};
ptint(struct stud * p)
{
p=p->next;
while(p!=NULL)
{
printf(PT);
p=p->next;
}
}
//////////////////////////////////////////////////////////
/**************创建链表****************/
struct stud *creat(void)
{
struct stud *p1,*p2,*head;
head=p2=(struct stud *)malloc(N); /*head,p2指向头节点*/
printf("请输入学号 姓名 成绩(学号输入0结束)\n");
p1=(struct stud *)malloc(N); /*p1指向第一个节点*/
scanf("%d %s %f",&p1->num,&p1->name,&p1->score);
while(p1->num!=0)
{
p2->next=p1; /*将新节点连接到表尾*/
p2=p1; /*p2指向新的表尾*/
p1=(struct stud *)malloc(N); /*p1指向新申请的节点*/
scanf("%d %s %f",&p1->num,&p1->name,&p1->score);
}
p2->next=NULL; /*表尾节点next域置空*/
free(p1); /*释放无效节点*/
return head;
}
/////////////////////////////////////////////////////////
/****************链表节点插入********************/
int insert(struct stud *p0)
{
struct stud *p;
p=(struct stud *)malloc(N); /*p指向新申请的节点*/
printf("请输入要插入的学号 姓名 成绩 \n");
scanf("%d %s %f",&p->num,&p->name,&p->score);
while(p0->next != NULL && p0->next->num < p->num )
p0 = p0->next; /*继续查找插入位置*/
if(p0->next != NULL && p0->next->num == p->num) /*找到重号*/
{
free(p); /*释放新节点的存储空间*/
return 0; /*不插入返回0*/
}
p->next = p0->next; /*后继节点链接到新节点之后*/
p0->next = p; /*新节点链接到前驱节点之后*/
return 1;
}
/////////////////////////////////////////////////////////
/******************链表节点的删除*********************/
int delete(struct stud *p0)
{
long num;
struct stud *p;
p=p0->next;
if(p == NULL) return 0; /*只有头结点为空表,不能删除返回0*/
printf("请输入要删除的学号 \n DNO:");
scanf("%d",&num);
while(p != NULL)
{
if(p->num == num) /* 找到要删除的节点 */
{
p0->next = p->next; /* 后续节点链接到前驱节点之后 */
free(p);
return 1;
}
p0 = p;
p = p->next; /* 推移指针继续查找 */
}
return 0; /* 未找到要删除的节点返回0 */
}
///////////////////////////////////////////////////////////////////
/****************************主函数*********************************/
void main()
{
struct stud *head,*p;
head = creat();
print(head);
p = find(head);
if(p) ptintf(PT);
else printf("没有找到!\n");
if(insert(head))
printf("已经成功插入 \n");
else
print(head);
if(delete(head))
ptintf("已经真确删除\n");
else
printf("要删除的节点不存在 \n");
print(head);
}