链表的基本操作(包含创建,查找,删除等)

#include<iostream>
using namespace std;

#define OK 1
#define ERROR -1

typedef char Elemtype;
typedef int Status;

typedef struct LNode
{
	Elemtype data;
	struct LNode *next;
}LNode, *Linklist;

Status CreateList(Linklist &L)
{
	Linklist p,q;
	Elemtype data;
	L = (Linklist)malloc(sizeof(LNode));
	L->next = NULL;
	q = L;
	while((data = getchar()) != '#')
	{
		p = (Linklist)malloc(sizeof(LNode));
		p->data = data;
		q->next = p;
		q = p;
	}
	q->next = NULL;
	return OK;
}

void PrintList(Linklist &L)
{
	Linklist p;
	p = L->next;
	while(p)
	{
		cout<<p->data<<" ";
		p = p->next;
	}
	cout<<endl;
}

Status GetElem(Linklist L,Elemtype *str)
{
	int count,i;
	Linklist p;
	p = L->next;
	count = 1;					//count计数
	cout<<"请输入查找编号"<<endl;
	cin>>i;
	while(p && count < i)
	{
		p = p->next;
		count++;
	}
	if(count > i)
		return ERROR;
	*str = p->data;
	cout<<"第"<<i<<"个元素为:"<<*str<<endl;
	return OK;
}

//删除链表中的元素
Status DeleList(Linklist &L,Elemtype *str)
{
	int i,count = 0;
	Linklist pr,p;
	pr = L;
	cout<<"请输入要删除的编号"<<endl;
	cin>>i;
	while(pr && count< i - 1)
	{
		pr = pr->next;
		count ++;
	}
	p = pr->next;
	*str = p->data;
	pr->next = p->next;
	cout<<"删除的元素为:"<<*str<<endl;
	return OK;
}

//在指定位置插入元素
Status InsertList(Linklist &L)
{
	int i,count = 0;
	char str;
	Linklist pr,p;				//pr为要插入的前一个结点
	pr = L;
	cout<<"请输入要插入的位置:"<<endl;
	cin>>i;
	cout<<"请输入要插入的元素:"<<endl;
	cin>>str;
	while(pr && count < i-1)
	{
		pr = pr->next;
		count ++;
	}
	p  = (Linklist)malloc(sizeof(LNode));
	p->data = str;
	p->next = pr->next;
	pr->next = p;
	return OK;
}

Status CompList(Linklist L)
{
	char str;
	int mark = 1;
	int count = 0;
	Linklist p;
	p = L;
	cout<<"请输入要查询的元素:"<<endl;
	cin>>str;
	while(p->next)
	{
		p = p->next;
		count++;
		if(p->data == str)
		{
			mark = 0;
			return count;
		}
	}
	if(mark == 1)
	{
		cout<<"未找到此元素"<<endl;
		return ERROR;
	}

}
int main()
{
	int findmark;
	char Gstr,Dstr;
	Linklist L;
	CreateList(L);
	PrintList(L);
	GetElem(L,&Gstr);

	DeleList(L,&Dstr);
	PrintList(L);

	InsertList(L);
	PrintList(L);

	findmark = CompList(L);
	cout<<findmark<<endl;
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值