#include <stdio.h>
#include <stdlib.h>
struct People
{
char Name[40];
int Number;
struct People *pNext;
};
int iCount;
struct People *Create()
{
struct People *pHead=NULL;
struct People *pEnd,*pNew;
iCount=0;
printf("Please Enter Name and Number:\n");
pEnd=pNew=(struct People*)malloc(sizeof(struct People));
scanf("%s",&pNew->Name);
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 People*)malloc(sizeof(struct People));
scanf("%s",&pNew->Name);
scanf("%d",&pNew->Number);
}
free(pNew);
return pHead;
}
void Print(struct People *pHead)
{
struct People *pTemp;
int iIndex;
printf("----------The Information Has %d----------\n",iCount);
pTemp=pHead;
iIndex=0;
while(pTemp!=NULL)
{
iIndex++;
printf("The NO%d is: \n",iIndex);
printf("The Name is:%s\n",pTemp->Name);
printf("The Number is %d\n",pTemp->Number);
pTemp=pTemp->pNext;
}
}
struct People *Insert(struct People *pHead)
{
struct People *pNew;
printf("Insert mumber at first\n");
pNew=(struct People*)malloc(sizeof(struct People));
scanf("%s",&pNew->Name);
scanf("%d",&pNew->Number);
pNew->pNext=pHead;//新节点指向头节点
pHead=pNew;//头指针指向新节点
iCount++;
return pHead;
}
//下面是删除代码
void Delete(struct People *pHead,int iTndex)//pHead 表示头结点,iTndex 表示要删除的节点
{
int i;//控制循环变量
struct People* pTemp;//临时指针
struct People* pPre;//表示要删除节点前的节点
pTemp=pHead;//得到头节点
pPre=pTemp;
printf("---delete NO%d mumber---",iIndex);
for(i=1;i<iIndex;i++)//循环,让pTemp指向要删除的节点
{
pPre=pTemp;
pTemp=pTemp->pNext;
}
pPre->pNext=pTemp->pNext;//连接删除后两边的节点
free(pTemp);
iCount--;
}
//NEW
int main()
{
struct People *pHead;
pHead=Create();
pHead=Insert(pHead);
Delete(pHead,2);
Print(pHead);
return 0;
}
把删除代码去掉后,运行正常,
但是加上以后就不正常了。
//iIndex 应该是与上下两个操作不违背的吧,所以不晓得问题出在哪。