实现一个简单的链表
#include<iostream>
#include<cstdio>
#include<cstdlib>
using namespace std;
typedef struct jiaowu
{
long num; //学号
float score; //成绩
struct jiaowu *next;
}Node;
//创建头结点,赋初值为0
Node* CreateInfoNode()
{
Node *pHead=NULL;
pHead=(Node*)malloc(sizeof(Node));
if(NULL==pHead)
{
return NULL;
}
pHead->num=0;
pHead->score=0;
pHead->next=NULL;
return pHead;
}
//链表中加入数据
void PushBackNode(Node* pHead,long num,float score)
{
if(NULL==pHead)
{
return;
}
Node *pNode=NULL;
Node *pNewNode=NULL;
pNode=pHead;
while(pNode->next!=NULL)
{
pNode=pNode->next;
}
pNewNode=(Node*)malloc(sizeof(Node));
if(NULL==pNewNode)
{
return;
}
pNewNode->num=num;
pNewNode->score=score;
pNode->next=pNewNode;
pNewNode->next=NULL;
return;
}
//查找
Node *FindNode(Node *pHead,long num)
{
if(NULL==pHead)
{
return NULL;
}
Node *pNode=pHead;
while(NULL!=pNode)
{
if(pNode->num==num)
{
break;
}
pNode=pNode->next;
}
return pNode;
}
//修改
void ChangeNode(Node *pHead,int num,float score)
{
if(NULL==pHead)
{
return;
}
Node *pNode=pHead;
while(NULL!=pNode)
{
if(pNode->num==num)
{
pNode->score=score;
printf("change success!\n");
return;
}
pNode=pNode->next;
}
printf("Not Find!\n");
}
//打印
void PrintNode(Node *pHead)
{
Node *pNode=pHead->next;
while(NULL!=pNode)
{
printf("%ld %.2f\n",pNode->num,pNode->score);
pNode=pNode->next;
}
}
//销毁
void DestroyNode(Node* pHead)
{
Node* tmp=NULL;
while(NULL!=pHead)
{
tmp=pHead->next;
free(pHead);
pHead=tmp;
}
}
int main()
{
Node *pHead=NULL;
pHead=CreateInfoNode();
long num=0;
float score=0;
while(1)
{
cin>>num;
if(num==0)
{
break;
}
cin>>score;
PushBackNode(pHead,num,score);
}
Node *p=FindNode(pHead,101);
if(NULL!=p)
{
printf("Find:\n");
printf("%ld %.2f\n",p->num,p->score);
}
ChangeNode(pHead,101,99.9);
printf("\nPrint:\n");
PrintNode(pHead);
DestroyNode(pHead);
system("pause");
return 0;
}