程序代码:
#include"stdafx.h"
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
struct CNode
{
CNode()
{
nAge = 0;
pNext = NULL;
memset(szName, 0, sizeof(szName));
}
CNode(int nage, char szname[], CNode* pnext)
{
nAge = nage;
strcpy(szName, szname);
pNext = pnext;
}
int nAge;
char szName[32];
CNode *pNext;
};
struct student
{
CNode* pHead; //头
CNode* pTail; //尾
int nCount; //学生个数
};
//初始化
void Init(student& theStud)
{
theStud.nCount = 0;
theStud.pHead = theStud.pTail = NULL;
}
//添加学生
void MyAdd(student& theStud)
{
CNode theNode;
printf("请输入学生年龄: ");
fflush(stdin);
scanf("%d", &theNode.nAge);
printf("请输入学生姓名: ");
fflush(stdin);
scanf("%31s", &theNode.szName[0]);
printf("\r\n");
CNode *pNewNode = (CNode *)malloc(sizeof(theNode));
if(pNewNode == NULL)
{
return;
}
pNewNode->nAge = theNode.nAge;
strcpy(pNewNode->szName, theNode.szName);
//头结点为NULL,表示还没有添加数据
if(theStud.pHead == NULL)
{
theStud.pHead = pNewNode;
theStud.pHead->pNext = NULL;
}
else if(theStud.pTail != NULL)
{
pNewNode->pNext = NULL;
theStud.pTail->pNext = pNewNode;
}
theStud.pTail = pNewNode;
theStud.nCount++;
}
//显示刚刚输入的数据
void MyDisplay(student& theStud)
{
CNode *pCurNode = NULL;
pCurNode = theStud.pHead;
while(pCurNode)
{
printf("学生年龄: %d\r\n", pCurNode->nAge);
printf("学生姓名: %s\r\n", pCurNode->szName);
printf("\r\n");
pCurNode = pCurNode->pNext;
}
}
//释放申请的空间
void MyRelease(student& theStud)
{
CNode *pCurNode = theStud.pHead;
CNode *pTempNode = NULL;
while(pCurNode)
{
pTempNode = pCurNode->pNext;
if(pCurNode)
{
delete pCurNode;
pCurNode = pTempNode;
}
}
}
void main()
{
student theStudent;
CNode theNode;
//初始化
Init(theStudent);
//以下增加3个学生信息
int i = 0;
while(i < 2)
{
printf("增加第%d个学生信息: \r\n", i+1);
MyAdd(theStudent);
i++;
}
//显示刚刚输入的数据
MyDisplay(theStudent);
//释放申请的空间
MyRelease(theStudent);
}