#include <stdio.h>#include <stdlib.h>#include <malloc.h>struct Student{ char cName[20]; int iNumber; struct Student *pNext; //指向下一個結點的指標};int iCount; //全域變數表示鏈表長度struct Student *Create(){ struct Student *pHead = NULL; //初始化鏈表頭指標為空白 struct Student *pEnd,*pNew; iCount = 0; //初始化鏈表長度 pEnd = pNew = (struct Student*)malloc(sizeof(struct Student)); 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; //跟蹤新加入的節點 pHead = pNew; //頭指標指向新結點 } else { pNew->pNext = NULL; //新結點的指標為空白 pEnd->pNext = pNew; //原來的尾結點指向新結點 pEnd = pNew; //*pEnd指向新結點 } pNew = (struct Student*)malloc(sizeof(struct Student)); //再次分配結點記憶體空間 scanf("%s",pNew->cName); scanf("%d",&pNew->iNumber); } free(pNew); //釋放沒有用的空間 return pHead;};void Print(struct Student *pHead){ struct Student *pTemp; //迴圈所用的臨時指標 int index = 1; //表示鏈表中的結點序號 printf("----the list has %d member:---\n",iCount); printf("\n"); pTemp = pHead; //指標得到首節點的地址 while(pTemp != NULL) { printf("the NO%d member is:\n",index); printf("the name is: %s\n",pTemp->cName); printf("the number is: %d\n",pTemp->iNumber); printf("\n"); pTemp = pTemp->pNext; //移動臨時指標到下一結點 index++; }}struct Student *Insert(struct Student *pHead){ struct Student *pNew; //指向新分配的空間 printf("-----Insert member 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("---delet NO%d member----\n",ilndex); for(i = 1;i < ilndex;i++) { pPre = pTemp; pTemp = pTemp->pNext; } pPre->pNext = pTemp->pNext; //串連刪除節點兩邊的節點 free(pTemp); //釋放掉要刪除的節點的記憶體空間 iCount--; //減少鏈表中的元素個數}int main(){ struct Student *pHead; pHead = Create(); pHead =Insert(pHead); Delete(pHead,2); Print(pHead); return 0;}