/*-----------------------------------------------------*/ #include<malloc.h> int n=0;/*n为全局变量,用来计算链表的结点个数*/ /*-----------------------------------------*/ struct student *p1; while(p2->number!=0) if(n==1) /*是否开辟的是第一个结点*/ p1=p2; /*-------------------------------------------------*/ }
/*--------------单链表的创建、插入、删除、倒置操作-----------*/
/*--------------written by redfire250-----2005.5.10----*/
/*-----------------------------------------------------*/
#include<stdio.h>
#define null 0
struct student
{
long number;
char name[20];
long score;
struct student *next;
};
/*--------------创建结点函数creat()--------*/
/*-----------------------------------------*/
struct student *creat()
{
struct student *p2;
struct student *head=null;
p1=p2=(struct student *)malloc(sizeof(struct student));/*开辟一段可用内存单元*/
printf("please input the student's number name and the score:\n");
scanf("%ld%s%ld",&p2->number,p2->name,&p2->score);
{
n++;
head=p2;
else
p1->next=p2;
p2=(struct student *)malloc(sizeof(struct student));
printf("input the number the name and the score:\n");
scanf("%ld%s%ld",&p2->number,p2->name,&p2->score);
}
p1->next=null;
return(head);
}
/*------------------------------------------*/
/*--------------查看链表内容函数view()------*/
/*------------------------------------------*/
view(struct student *head)
{
struct student *p;
p=head;
while(p->next!=null)
{
printf("%ld %s %ld\n",p->number,p->name,p->score);
p=p->next;
}
printf("%ld %s %ld\n",p->number,p->name,p->score);
}
/*--------------插入结点函数(前插)insert()-------*/
/*-------------------------------------------------*/
insert(struct student *head,int num) /*head为链表头指针,num插入链表位置*/
{
int t=1;
struct student *p1,*p2;
p1=head;
if (num>n||num<0)
{
printf("input error!!!\n");
return 0;
}
while(t<num-1) /*找到要插入结点的前一个结点*/
{
p1=p1->next;
t++;
}
p2=(struct student *)malloc(sizeof(struct student));
printf("input the number the name and the score:\n");
scanf("%ld%s%ld",&p2->number,p2->name,&p2->score);
p2->next=p1->next;
p1->next=p2;
n++;
/*------------------------------------------*/
/*------------ 删除结点函数delnode()--------*/
/*-----------------------------------------*/
delnode(struct student *head,int node)
{
int t=1;
struct student *p1,*p2;
p2=head;
if (node>n||node<1)
{
printf("error!!! the node is not exist!");
return 0;
}
while(t<node-1) /*找到要删除结点的前一个结点*/
{
p2=p2->next;
t++;
}
p1=p2->next->next; /*找到要删除结点的后一个结点*/
free(p2->next); /*释放要删除的结点空间(删除)*/
p2->next=p1; /*前一结点指向后一结点*/
n--;
}