c++数据结构 单链表的功能实现

显示所有节点数据:

void all(Student *p)
{
	cout << "显示全部节点数据" << endl;
	while (p != NULL)
	{
		cout << p->num << setw(10) << p->name << endl;
		p = p->next;
	}
}

取值:

void getelem(Student *p, int i)//取值
{
	cout << "取值" << endl;
	int j = 1;
	while (p != NULL && j < i)
	{
		p = p->next;
		j++;
	}
	if (p != NULL) cout << p->num << setw(10) << p->name << endl;
	else cerr << "该位置无元素" << endl;
}

查找:

bool find(Student *p, string num, string name)
{
	cout << "查找" << endl;
	while (p!=NULL&&num!=p->num&&name!=p->name)
	{
		p->next;
	}
	if (p != NULL) 
	{ 
		cout << p->num << setw(10) << p->name << endl; 
		cout << "成功找到" << endl; 
		return true;
	}
	else cout << "查无此人" << endl;
}

插入数据:

void insert(Student *p, Student *in,int i)
{
	cout << "插入" << endl;
	int j = 1;
	while (j < i&&p != NULL)
	{
		j++;
		p = p->next;
	}
	if (j < i) cout << "找不到该节点" << endl;
	else
	{
		in->next = p->next;
		p->next = in; 
		cout << "插入完成" << endl;
	}
}

删除数据:

void deletes(Student *p, int i)
{
	int j = 1;
	while (p != NULL && j < i)
	{
		j++;
		p = p->next;
	}
	if (j < i) cout << "该节点为空,无法删除" << endl;
	else 
	{
		Student *q = p->next;
		p->next = q->next;
		//delete q;
		cout << "删除成功" << endl;
	}
}
#include "pch.h"
#include<iostream>
#include<algorithm>
#include<iomanip>
#include<string>
#include<cstring>
using namespace std;
struct Student
{
	string num;//学号
	string name;//姓名
	struct Student *next;
};
void all(Student *p);//显示所有数据
void getelem(Student *p, int i);//取值
bool find(Student *p, string num, string name);//查找数据
void insert(Student *p, Student *in,int i);//插入数据
void deletes(Student *p,int i);//删除数据
int main()
{
	struct Student a, b, c, *head, *p;
	a.num = "1";
	a.name = "first";
	a.next = &b;
	b.num = "2";
	b.name = "second";
	b.next = &c;
	c.num = "3";
	c.name = "third";
	c.next = NULL;//对结构中各数据赋值并链接节点
	head = &a;
	p = head;
	all(p);
	cout << endl;
	getelem(p, 2);
	cout << endl;
	find(p, "1", "first");
	cout << endl;
	struct Student in;
	in.num = "4";
	in.name = "fourth";
	insert(p, &in, 2);
	all(p);
	cout << endl;
	deletes(p, 2);
	all(p);
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值