从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;
}
相关推荐
太理摆烂哥4 小时前
数据结构之红黑树
数据结构
hnjzsyjyj4 小时前
洛谷 B4241:[海淀区小学组 2025] 统计数对 ← STL map
数据结构·stl map
泡沫冰@5 小时前
数据结构(18)
数据结构
苏纪云7 小时前
数据结构期中复习
数据结构·算法
初听于你7 小时前
Java五大排序算法详解与实现
数据结构·算法·排序算法
多多*7 小时前
牛客周赛 Round 117 ABCDE 题解
java·开发语言·数据结构·算法·log4j·maven
熬夜敲代码的小N7 小时前
仓颉ArrayList动态数组源码分析:从底层实现到性能优化
数据结构·python·算法·ai·性能优化
大白的编程日记.8 小时前
【高阶数据结构学习笔记】高阶数据结构之B树B+树B*树
数据结构·笔记·学习
ゞ 正在缓冲99%…9 小时前
leetcode1547.切棍子的最小成本
数据结构·算法·leetcode·动态规划
2401_841495649 小时前
【LeetCode刷题】移动零
数据结构·python·算法·leetcode·数组·双指针法·移动零