很久沒有寫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;
}