从0开始的数据结构的书写-------线性表(单链表)

(复习考研的休息区,心血来潮,写点代码)

三个规则:

1、不使用c++ stl库进行书写

2、最好基于严蔚敏老师的数据结构

3、最好使用malloc和realloc动态分配内存

(如果有问题或者是有没有实现的操作,请大家提出来)

cpp 复制代码
// 链表实现 
#include<iostream>
#include<cstring>

using namespace std;

#define N 100
#define OK true 
#define ERRORINT 0x3f3f3f3f3f
#define ERROR false

typedef struct LNode
{
	// 单链表 
	int data;
	struct LNode *ne;
}LNode , *LinkList;


void InitList(LinkList &L)
{
	L = (LinkList)malloc(sizeof(LNode));
	L -> ne = NULL; // 建立带头节点的单链表 
}

// 头插法 
void HeadInsert(LinkList &L)
{
	for(int i = 1;i <= 10;i ++)
	{
		LinkList p = (LinkList)malloc(sizeof(LNode));
		p -> data = i;
		p -> ne = L -> ne;
		L -> ne = p;
	}
} 

// 尾插法
void TailInsert(LinkList &L)
{
	LinkList now = L;
	for(int i = 1;i <= 10;i ++)
	{
		LinkList p = (LinkList)malloc(sizeof(LNode));
		p -> data = i;
		now -> ne = p;
		now = p;
	}
	now -> ne = NULL;
} 

// 插入到第idx位置 
bool InsertList(LinkList &L , int idx , int e)
{
	LinkList p = L;
	int i = 0;
	while(p && i < idx - 1) 
	{
		p = p -> ne;
		i ++;
	}
	if(!(p -> ne) || i > idx - 1) return ERROR;
	
	cout << "插入数据" << e << endl; 
	LinkList s = (LinkList) malloc(sizeof(LNode));
	s -> data = e;
	s -> ne = p -> ne;
	p -> ne = s;
	
	return OK;
}

// 删除节点 
int DeleteList(LinkList &L , int idx)
{
	LinkList p = L;
	int i = 0;
	while(p && i < idx - 1)
	{
		p = p -> ne;
		i ++;
	}
	if(!p || i > idx - 1) return ERROR;
	int e = p -> ne -> data;
	cout << "删除节点" << e << endl; 
	p -> ne = p -> ne -> ne;
	return e;
}

void print(LinkList L)
{
	LinkList p = L;
	cout << "当前链表数据为:";
	p = p -> ne;
	bool f = false;
	while(p)
	{
		if(f) cout << "->";
		cout << p -> data;
		f = true;
		p = p -> ne;
	}
	cout << endl;
}

int main()
{
	LinkList L;
	InitList(L);
	
	// HeadInsert(L);
	// print(L)
	TailInsert(L);
	print(L);
	
	InsertList(L , 3 , 11);
	InsertList(L , 5 , 12);
	print(L);
	DeleteList(L , 6);
	DeleteList(L , 3);
	print(L);
	return 0;
}
相关推荐
浅念-1 天前
刷穿LeetCode:BFS 解决 Flood Fill 算法
数据结构·c++·算法·leetcode·职场和发展·bfs·宽度优先
im_AMBER1 天前
手撕hot100之矩阵!看完这篇就AC~
javascript·数据结构·线性代数·算法·leetcode·矩阵
如君愿1 天前
考研复习 Day 30 | 习题--计算机网络 第五章(运输层 上)、数据结构 图(上)
数据结构·计算机网络·课后习题
weixin_421725261 天前
C语言中volatile关键字怎么用C语言volatile在多线程中的作用
c语言·数据结构·运算符优先级·变量命名·volatile关键字
05候补工程师1 天前
【408 从零到一】线性表逻辑特征、存储结构对比与 C/C++ 动态内存分配避坑指南
c语言·开发语言·数据结构·c++·考研
努力努力再努力wz1 天前
【MySQL 进阶系列】拒绝滥用root:从 mysql.user 到权限校验,带你彻底理解用户管理与授权机制!
android·c语言·开发语言·数据结构·数据库·c++·mysql
炸膛坦客1 天前
嵌入式 - 数据结构与算法:(1-4)数据结构 - 单链表的两个核心缺点(引入循环/双向链表)
c语言·数据结构·链表
Hesionberger1 天前
LeetCode 78:子集生成全攻略
java·开发语言·数据结构·python·算法·leetcode·职场和发展
上弦月-编程1 天前
高效编程利器:转移表技术解析
c语言·开发语言·数据结构·算法·排序算法
薇茗1 天前
【初阶数据结构】 左右逢源的分支诗律 二叉树2
c语言·数据结构·算法·二叉树