链表的增删改查

#include<bits/stdc++.h>
using namespace std;
int a, n, z,k,where;
struct node
{
	int data;
	node *next;
};
node *cz;
node *creat(int n)
{
	node *p,*q=NULL,*head=NULL;
	cout << "请输入元素:" << endl;
	for (int i = 0; i < n; i++)
	{
		cin >> a;
		p = (node *)malloc(sizeof(node));
		if (p == NULL)
		{
			cout << "创建失败!" << endl << "程序即将退出" << endl;
			exit(0);
		}
		else
		{

			p->data = a;
			p->next = NULL;
			if (head == NULL)
			{
				head = p;
			}
			else
			{
				q->next = p;
			}
			q = p;
		}
	}
	return head;
}
node *search(int k,node *head)
{
	node *q = head;
	while (q != NULL)
	{
		if (q->data == k)
		{
			return q;
		}
		q=q->next;
	}
	return NULL;
}
void deletenode(int where, node *head)
{
	node *p,*q,*begin=NULL;
	begin = head;
	p = search(where, head);
	while (begin->next != p)
	{
		begin = begin->next;
	}
	q = begin;
	if (p->next!= NULL)
	{
		q->next = p->next;//找到的结点
	}
	else
	{
		q->next = NULL;
		free(p);
		return;
	}
	free(p);
	return;
}
void insert(int where, node *head)
{
	int k;
	cout << "请输入要插入的元素:" << endl;
	cin >> k;
	node *p, *q,*t,*begin=NULL;
	begin = head;
	p= search(where, head);
	q = p->next;
	if (p!= NULL)
	{
		t = (node *)malloc(sizeof(node));
		t->data = k;
		t->next = q;
		p->next = t;
	}
	else
	{
		t = (node *)malloc(sizeof(node));
		t->data = k;
		t->next = NULL;
		p->next = t;
	}
}
void print(node *head)
{
	node *p = head;
	while (p!= NULL)
	{
		cout <<p->data << " ";
		p = p->next;
	}
	cout << endl;
	return;
}
void selct(int n,node *head)
{
	if (n == 1)
	{
		cout << "请输入要查询的元素: "<<endl;
		cin >> k;
		cz = search(k, head);
		if (cz != NULL)
		{
			int z =0;
			cout << "元素" << k << "在链表中的位置是: ";
			node *p = head;
			while (p != NULL)
			{
				if (p == cz)
				{
					break;
				}
				else
				{
					z++;
				}
				p = p->next;
			}
			cout << z+1<<endl;
		}
		else
		{
			cout << "不存在此元素"<<endl;
		}
	}
	else if (n == 2)
	{
		cout << "请输入要删除的元素: "<<endl;
		cin >> where;
		deletenode(where, head);
		cout << "删除成功!" << endl;
	}
	else if(n==3)
	{
		cout << "请输入要在那个元素后插入新的元素: "<<endl;
		cin >> where;
		insert(where, head);
		cout << "插入成功"<<endl;
	}
	else if(n==4)
	{
		print(head);
	}
	else if (n == 5)
	{
		cout << "请输入要进行的操作" << endl << "1:查询元素" << endl << "2:删除元素" << endl << "3:插入元素" << endl << "4:输出链表的内容" << endl<<"其他任意键退出"<<endl;
	}
	else
	{
		exit(0);
	}
}
int main()
{
	node *head;
	cout << "请输入结点的个数: "<<endl;
	cin >>n;
	head = creat(n);
	cout << "请输入要进行的操作" << endl << "1:查询元素" << endl << "2:删除元素" << endl << "3:插入元素" << endl << "4:输出链表的内容"<<endl<<"5:输出可操作内容"<<endl<<"其他任意键退出"<<endl;
	while (cin>>n)
	{
		selct(n,head);
	}
	return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值