单链表的创建、插入、删除、打印。代码详解
#include <stdio.h>
#include <stdlib.h>
struct Student
{
char cName[20]; //数字域
int iNumber;
struct Student* pNext; //定义指针域
};
int iCount; //链表的长度,全局变量
struct Student* Creat() //创建链表
{
struct Student* pHead =NULL; //头结点不存放数据,故为空
struct Student* pNew, * pEnd; //定义尾结点和新节点
iCount = 0;
pEnd = pNew = (struct Student*)malloc(sizeof(struct Student));
//用malloc动态分配储存空间,返回值为地址
printf("please first enter Name , then Number \n");
scanf("%s", &pNew->cName);
scanf("%d", &pNew->iNumber);
while (pNew->iNumber != 0)
{
iCount++;
if (iCount == 1)
{
pNew -> pNext = pHead; //指针域为空
pEnd = pNew; //一代新人换旧人,刚刚定义的pNew变成尾结点
pHead = pNew; //头结点指向新节点
}
else
{
pNew->pNext = NULL; //参考上方的注释
pEnd->pNext = pNew;
pEnd = pNew;
}
pNew = (struct Student*)malloc(sizeof(struct Student));
scanf("%s", &pNew->cName);
scanf("%d", &pNew->iNumber);
}
free(pNew);
/*作者感觉这一步没有必要,因为上面输入一组数据,开辟一个地址,
当输入终止条件,iNumber=0,进行while判断,不满足条件,跳出循环,
所以不会开辟空节点。但是,这一步写上也不算错。使用malloc时用free是一种好习惯*/
return pHead;
}
void Print(struct Student* pHead) //打印链表
{
struct Student* pTemp; //创建临时指针
int ilndex=1; //表示链表中节点的序号
printf("----the List has %d number\n", iCount);
printf("\n");
pTemp = pHead; //指针得到首节点的地址
while (pTemp != NULL)
{
printf("the ON%d member is:\n",ilndex);
printf("the name is %s\n", pTemp->cName);
printf(" the inumber is %d\n", pTemp->iNumber);
printf("\n");
pTemp = pTemp->pNext;
ilndex++;
}
}
struct Student* Insert(struct Student* pHead) //插入,本题使用是头插法
{
struct Student* pNew;
printf("------Insert number at first\n");
pNew = (struct Student*)malloc(sizeof(struct Student));
scanf("%s", &pNew->cName);
scanf("%d", &pNew->iNumber);
pNew->pNext = pHead; //头插法是在头结点的前面,故新节点的后驱是头结点
pHead = pNew; //原来的头结点变成了首节点,而新节点变成了头结点
iCount++; //链表长度增加
return pHead;
}
void Delete(struct Student* pHead, int ilndex) //pHead表示头结点,ilndex表示要删除节点的下标
{
int i;
struct Student* pTemp;
struct Student* pPre; //要删除节点前的节点,理解不了的看看下方的循环
pTemp = pHead;
pPre = pTemp;
printf("----delete NO%d member----\n", ilndex);
for (i = 1; i < ilndex; i++) //for循环使得pTemp指向要删除的节点
{
pPre = pTemp;
pTemp = pTemp->pNext;
}
pPre->pNext = pTemp->pNext; //连接删除节点两边的节点
free(pTemp);
iCount--;
}
int main()
{
struct Student* pHead;
pHead = Creat();
pHead = Insert(pHead);
Delete(pHead, 2);
Print(pHead);
return 0;
}