栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

王道考研数据结构之链表的增删改查

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

王道考研数据结构之链表的增删改查

#include
#include
typedef struct Node{
    int data;
    struct LNode *next;
}LNode,*Linklist;
//头插法
Linklist head_InitList(Linklist &L){
	printf("请依次输入你要插入的元素:");
	LNode *s;
	int data;
	L = (LNode*)malloc(sizeof(LNode));
	L->next=NULL;                   
	scanf("%d",&data);
	while(data!=9999){
		s = (LNode*)malloc(sizeof(LNode));
		s->next=L->next;
		s->data=data;
		L->next=s;
		scanf("%d",&data);
	}
	return L; 
}
//尾插法 
Linklist tail_InitList(Linklist &L){
	printf("请依次输入你要插入的元素:");
	int data;
	L = (LNode*)malloc(sizeof(LNode));
	LNode *s,*r=L;
	scanf("%d",&data);
	while(data!=9999){
		s=(LNode*)malloc(sizeof(LNode));
		s->data=data;
		r->next=s;
		r=s;
		scanf("%d",&data);
	}
	r->next=NULL; 
	return L;
}
//求表长 
void Length(Linklist L){
	int a=0;
	LNode *p;
	p=L;
	while(p->next!=NULL) 
	{
		a+=1;
		p=p->next;
	}
	printf("该单链表的表长为:%dn",a);	 
}
//按值查找操作 
LNode *LocateElem(LNode *L,int e){

	LNode *p=L->next;
	while(p&&p->data!=e) p=p->next;
	return p;
}
//按位查找操作 
LNode *GetElem(Linklist L,int i){
	LNode *p;
	p=L->next;
	if (i==0) return L;
	if (i<0) return NULL;
	for(int j=1;jnext;
	return p; 
}
//插入操作 
Linklist ListInsert(Linklist &L,int i,int e){
	LNode *p,*s;
	p=GetElem(L,i-1);
	s->next=p->next;
	p->next=s;
	s->data=e;
}
//按位删除操作 
Linklist ListDelete(Linklist &L,int i){
	LNode *p,*s;
	p=GetElem(L,i-1);
	s=p->next;
	p->next=p->next->next; 
	free(s);
	
}
//输出操作 
void PrintList(Linklist L){
	LNode *p;
	p=L->next;
	printf("该链表为:"); 
	while(p!=NULL){
		printf("%dt",p->data);
		p=p->next;
	}
	printf("n");
}
//判空操作 
void Empty(Linklist L){
	if(L->next!=NULL){
		printf("链表不为空n"); 
	}
	else{
		printf("链表为空n"); 
	}
}
//销毁链表操作 
void DestroyList(Linklist &L){
	LNode *p;
	while(L->next){
		p=L->next;
		L->next=p->next;
		free(p);
	}	
}
int main(){
	int score;
	Linklist L;

	int e,i;
	LNode *p;
	while(1){
		printf("请输入你的case:n1:头插法n2:尾插法n3:输出n4:求表长:n5:判断空链表n6:销毁链表n7:按值查找n8:按位查找n9:插入操作n10:删除操作n");
		printf("你的选择是:");
		scanf("%d",&score);
	    switch(score){
			case 1:head_InitList(L);break;
			case 2:tail_InitList(L);break;
			case 3:PrintList(L);break;
			case 4:Length(L);break;	
			case 5:Empty(L);break;
			case 6:DestroyList(L);break;
			case 7:scanf("%d",&e);p=LocateElem(L,e);printf("找到该节点为:%dn",p->data); break;
			case 8:scanf("%d",&e);GetElem(L,i);break;
			case 9:scanf("%d",&i);scanf("%d",&e);ListInsert(L,i,e);break;
			case 10:scanf("%d",&i);ListDelete(L,i);break;
			default:break;
	}
	}
	return 0;
} 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/832822.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号