一下是我从一本参考书 看到的代码,大家可以参考:
/*
1.链表的创建过程是一个动态的创建过程
链表不是一开始就设定好自身大小的,而是根据节点的多少决定的
2.mallo()函数
在内存中动态的分配指定大小的内存空间
返回一个指针,该指针指向分配的内存空间,出错则返回 NULL
3.calloc()函数
void *calloc(unsigned n,unsigned size);
在内存中动态分配n个长度为size 的连续内存空间爱数组。
该函数返回一个指针,该指针指向动态分配的连续内存空间,出错则返回 NULL
4.free()函数
释放内存空间
*/
#include
#include
//结构体
struct Student
{
char name[20];
int number;
struct Student *pNext;//指向下一个节点的指针
};
//定义全局变量,表示链表长度
int iCount;
//定义函数creat,用来创建列表
struct Student* creat()
{
struct Student *pHead=NULL;//初始化链表头指针为空
struct Student *pEnd,*pNew;
iCount=0;//初始化链表长度
pEnd=pNew=(struct Student *)malloc(sizeof(struct Student));//分配空间
printf("请输入姓名:\n");
scanf("%s",pNew->name);
printf("请输入学号:\n");
scanf("%d",&pNew->number);
while (pNew->number!=0) {
iCount++;
if (iCount==1) {
pNew->pNext=pHead;
pEnd=pNew;
pHead=pNew;
}
else
{
pNew->pNext=NULL;
pEnd->pNext=pNew;
pEnd=pNew;
}
pNew=(struct Student *)malloc(sizeof(struct Student));
printf("请输入姓名:\n");
scanf("%s",pNew->name);
printf("请输入学号:\n");
scanf("%d",&pNew->number);
}
free(pNew);
return pHead;
}
//输出链表
void show(struct Student *pHead)
{
struct Student *pTemp;
int iIndex=1;
printf("链表有成有%d个",iCount);
printf("\n");
pTemp=pHead;
while (pTemp != NULL) {
printf("the NO%d member is:\n",iIndex);
printf("the name is: %s\n",pTemp->name);
printf("the number is:%d",pTemp->number);
printf("\n");
pTemp=pTemp->pNext;
iIndex++;
}
}
//链表的插入操作
struct Student *Insert(struct Student *pHead)
{
struct Student *pNew;
printf("—Insert member at first- \n");
pNew=(struct Student*)malloc(sizeof(struct Student));
printf("请输入姓名:\n");
scanf("%s",pNew->name);
printf("请输入学号:\n");
scanf("%d",&pNew->number);
pNew->pNext=pHead;
iCount++;
return pHead;
}
//链表的删除
void delete(struct Student* pHead,int iIndex)
{
struct Student *pTemp;
struct Student *pPre;//要删除节点前的节点
pTemp=pHead;
pPre=pTemp;
printf("--delete NO%d member",iIndex);
for (int i=0; i
pPre=pTemp;
pTemp=pTemp->pNext;
}
pPre->pNext=pTemp->pNext;
free(pTemp);
iCount--;
}
int main(int argc, const char * argv[])
{
struct Student *pStu;
pStu=creat();
pStu=Insert(pStu);
delete(pStu, 2);
// printf("%s",pStu->name);
show(pStu);
return 0;
}