数据结构——单链表

1. 传作灵感

在学习数据结构的时候,如果不动手写代码,始终学不会,所以通过几个简单的函数,熟悉单链表,提升自己的代码能力。

2. 单链表的定义

cpp 复制代码
#include <iostream>
#include <string>
#include<stdlib.h>
#include<stdio.h>

using namespace std;  // 全局引入std命名空间

#define OK 1
#define ERR 0

//链表的定义
typedef struct Node
{
	char name[50];
	struct Node* next;
}node;

typedef node* Linklist;
typedef int Status;

3.读取链表中的元素

cpp 复制代码
//读取链表中的元素
Status GetElem(Linklist L, int i, char* e)
{
	int j;
	Linklist p;
	p = L->next;
	j = 1;
	while (p && j < i)
	{
		p = p->next;
		++j;
	}
	if (!p)
		return ERR;

	strcpy_s(e,50, p->name);

	return OK;
}

3. 插入一个节点

注意这里的参数,Linklist 本身已经是指向结构体的指针,这里使用的是Linklist * L,它是是一个二重指针。一维指针可以指向具体的变量,而在需要改变指针的指向的时候,则需要用二维指针。

cpp 复制代码
//插入一个节点
Status LinkInsertNode(Linklist * L, int i, const char* e)
{
	int j;
	Linklist p, s;
	p = *L;
	j = 1;
	while (p && j < i)
	{
		p = p->next;
		++j;

	}
	if (!p)
		return ERR;
	s = (Linklist)malloc(sizeof(node));

	strcpy_s(s->name, e);

	s ->next = p->next;
	p->next = s;
	return OK;


}

4. 删除一个节点

cpp 复制代码
//删除链表中的一个节点
Status LinkDeleteNode(Linklist* L, int i, char *e)
{
	int j = 1;
	Linklist p,q;
	p = *L;
	while (p && j < i)
	{
		p = p->next;
		++j;
	}
	if (!p)
		return ERR;

	q = p->next;
	p->next = q->next;

	strcpy_s(e, 50, q->name);
	free(q);

	return OK;



}

5. 清空链表

这里只是清空链表中的数据,但是保留了链表头

cpp 复制代码
//清空整个链表
Status ClearList(Linklist* L)
{
	Linklist p, q;
	p = (*L)->next;
	while (p)
	{
		q = p->next;
		free(p);
		p = q;
	}
	(*L)->next = NULL;
	return OK;
}

6. 调用实例

通过使用这几个函数,就可以熟悉链表的基本用法

cpp 复制代码
int main()
{
	Status Insertstatus;

	Linklist LL = (Linklist)malloc(sizeof(node));
	LL->next = NULL;

	// 插入3个节点
	LinkInsertNode(&LL, 1, "ZhangSan");
	LinkInsertNode(&LL, 2, "LiSi");
	LinkInsertNode(&LL, 3, "WangWu");
	LinkInsertNode(&LL, 4, "ZhaoLiu");

	// 读取第2个节点
	char buf[50];
	char buf1[50];
	if (GetElem(LL, 3, buf) == OK) {
		printf("第3个节点:%s\n", buf);  // 输出:LiSi
	}
	printf("删除节点之后!\n");

	LinkDeleteNode(&LL, 3, buf1);
	if (GetElem(LL, 3, buf) == OK) {
		printf("第3个节点:%s\n", buf);  // 输出:LiSi
	}


	return 0;
}
相关推荐
AI情绪识别开源6 小时前
检信 ALLEMOTION OS 加密打包可执行程序 — 全面测试报告版本: v1.3功能测试 / 性能测试 /
开发语言·数据结构·人工智能·功能测试
伟大的车尔尼13 小时前
贪心的概念
数据结构·算法·贪心
AI情绪识别开源13 小时前
检信AI高一分班分科智选评估系统 v2.0测试报告
开发语言·数据结构·人工智能·科技
CoderYanger14 小时前
A.每日一题:输入单词需要的最少按键次数 Ⅰ+Ⅱ
java·数据结构·算法·leetcode·面试
雪碧聊技术15 小时前
KMP算法详解
数据结构
positive_zpc18 小时前
进阶数据结构图——关键路径(四)
数据结构·图论·关键路径
孙克旭_18 小时前
单链表进阶实操:5 道常考面试题详细解析【Java 实现】
java·开发语言·数据结构·单链表
Chester_199919 小时前
CSP202206C.角色授权
开发语言·数据结构·c++·蓝桥杯
旖旎夜光20 小时前
LeetCode 238:除自身以外数组的乘积(前缀和) —— 题解
数据结构·c++·算法·leetcode·前缀和
一条大祥脚20 小时前
26杭电暑期第八场(后半)快读|快写|tarjan|路径DP|mex转化|扫描线|前缀和|二分图
数据结构·算法·tarjan·杭电多校·强联通分量·动态规划dp