很久没有写C语言了,今天突然回顾一下,就写了一个简答的单链表实现学生信息管理的增删查改,对与初学者来说可以参考!
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
using namespace std;
//表节点结构体
typedef struct LinkNode
{
char stu_no[10];//学号
char stu_name[10];//名字
struct LinkNode *next;
}LinkNode;
//初始化链表
LinkNode* Initial_LinkList(LinkNode *&L)
{
LinkNode *node = (LinkNode*)malloc(sizeof(LinkNode));
node->next = NULL;
}
//向链表中插入新节点
void InsertNode(LinkNode *&L,char *stu_no,char *stu_name)
{
if(L!=NULL)
{
LinkNode *node = (LinkNode*)malloc(sizeof(LinkNode));
strcpy(node->stu_no,stu_no);
strcpy(node->stu_name,stu_name);
node->next = NULL;
LinkNode *p;
p=L;
node->next=p->next;
p->next=node;
}
}
//打印链表节点信息
void printNode(LinkNode *L)
{
LinkNode *p=L->next;
while(p!=NULL)
{
printf("stu_no:%s stu_name:%s \n",p->stu_no,p->stu_name);
p=p->next;
}
}
//删除链表节点
void deleteNode(LinkNode *&L,char *num)
{
LinkNode *p,*s;
p=L;
while(p->next!=NULL)
{
if(strcmp(p->next->stu_no,num)==0)
{
s=p->next;
p->next=p->next->next;
free(s);
}
p=p->next;
}
}
//修改链表节点信息
void modify_Node(LinkNode *L,char *stu_no,char stu_name[])
{
LinkNode *p;
p=L->next;
while(p!=NULL)
{
if(strcmp(stu_no,p->stu_no)==0)
{
strcpy(p->stu_name,stu_name);
}
p=p->next;
}
}
int main()
{
int i=0;
LinkNode *L;
L=Initial_LinkList(L);
char stu_no[10],stu_name[10];
while(i<4)
{
cout<<"please enter stu_no:"<<endl;
scanf("%s",&stu_no);
cout<<"please enter stu_name:"<<endl;
scanf("%s",&stu_name);
InsertNode(L,stu_no,stu_name);
++i;
}
printNode(L);
printf("enter delete num:");
scanf("%s",&stu_no);
deleteNode(L,stu_no);
printNode(L);
printf("输入要修改的学号:");
scanf("%s\n",&stu_no);
printf("输入新姓名:");
scanf("%s\n",&stu_name);
modify_Node(L,stu_no,stu_name);
printNode(L);
return 0;
}