欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用链表实现学生管理系统实现学号的录入插入和删除

程序员文章站 2022-05-06 20:30:44
...
用链表实现学生管理系统实现学号的录入插入和删除
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
#include<windows.h>
typedef struct hgjkd
{
	int num;
	struct hgjkd *pnext;
}ints;
ints *pstu=NULL;
int n=0;
ints *create()
{
	ints*pnew=NULL;
	ints*phead=NULL;
	ints*ptail=NULL;
	int key1=1;
	while(key1==1)
	{
		pnew=(ints *)malloc(sizeof(ints));
		pnew->pnext=NULL;
		printf("Input the %d student's number:\n",n+1);
		scanf("%d",&pnew->num);
		if(pnew->num==0)
		{
			free(pnew);
			break;
		}
		if(phead==NULL)
		{
			phead=pnew;
			ptail=pnew;
		}
		else
		{
			ptail->pnext=pnew;
			ptail=pnew;
		}
		n+=1;
	}
	return phead;
} 
void print(ints *phead)
{
	printf("number:\n");
	do
	{
		printf("%d\n",phead->num);
		phead=phead->pnext;
	}while(phead->pnext!=NULL);
	printf("%d\n",phead->num);
}
void insert(ints*phead)
{
	int i,k;
	ints *ptemp=phead;
	ints *pold=NULL;
	ints *pnew=(ints *)malloc(sizeof(ints)); 
	pnew->pnext=NULL;
	while(1)
	{
		printf("请输入插入的节点:(0->%d)\n",n);
		scanf("%d",&k);
		if(k<0||k>n)
		{
			printf("输入数据不合法(0->%d)\n",n); 
			continue;
		}
		else
			break;
	}
	{}
	printf("Input the student's number:\n");
	scanf("%d",&pnew->num);
	for(i=1;i<k;i++)
		ptemp=ptemp->pnext;
	pold=ptemp->pnext;
	if(k==0)
	{
		pnew->pnext=phead;
		pstu=pnew;
	}
	else
	{
		if(k==n)
			ptemp->pnext=pnew;
		else
		{
			pnew->pnext=pold;
			ptemp->pnext=pnew;		
		} 
	}
	n+=1;
} 
void dell(ints*phead)
{
	int N,i;
	ints *ptemp=phead;
	ints *pdel=phead;
	while(1)
	{
		printf("请输入要删除的节点(1->%d):\n",n); 
		scanf("%d",&N);
		if(N>0&&N<=n)
			break;
		else
		{
			printf("请输入合法位置!(1->%d)\n",n);
			continue;
		} 
	}
	for(i=1;i<N-1;i++)
		ptemp=ptemp->pnext;
	pdel=ptemp->pnext;
	if(N==1)
	{
		pstu=ptemp->pnext;
		ptemp->pnext=NULL;
		free(ptemp);
	}
	else
	{
		if(N==n)
		{
			ptemp->pnext=NULL;
			free(pdel);
		}
		else
		{
			ptemp->pnext=pdel->pnext;
			pdel->pnext=NULL;
			free(pdel);
		}
	}
	n-=1;	
}
int menu()
{
	int key2;
	printf("********欢迎光临********\n");
	printf("1,创建新的链表\n");
	printf("2,插入新成员\n");
	printf("3,删除成员\n");
	printf("4,显示当前成员\n");
	printf("0,退出\n");
	printf("当前有 %d 名成员\n",n);
	printf("************************\n");
	while(1)
	{
		printf("请输入指令:\n");
		scanf("%d",&key2);
		if(pstu==NULL&&key2>1&&key2<5)
			printf("请先创建初始链表!\n");
		else
			break;
	}
	switch(key2)
	{
		case 0 :
		{
			printf("******欢迎下次使用******\n");
			return 0; 
			break;
		}
		case 1 :
		{
			pstu=create();
			system("pause");
			return 1; 
			break;
		}
		case 2 :
		{
			insert(pstu);
			system("pause");
			return 2; 
			break;
		}
		case 3 :
		{
			dell(pstu);
			system("pause");
			return 3; 
			break;
		}
		case 4 :
		{
			print(pstu);
			system("pause");
			return 4; 
			break;
		}
		default :
			{
				printf("输入指令有错,请重新输入!\n");
				Sleep(1800);
				return 5;
			}
	} 
}
int main()
{
	int key2=1;
	while(key2!=0)
	{
		system("cls");
		key2=menu();
	}
	free(pstu);
	return 0;
}


相关标签: C