栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

C++ 实现单链表

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

C++ 实现单链表

#include
#include
using namespace std;
#define OVERFLOW -2
#define FALSE 0
#define TRUE 1
#define MAXSIZE 10
#define OK 1
#define ERROR -1

// 单链表结点
typedef struct Node{
Node *next; // 头结点,分两种一种有头节点,一种无头结点(直接指向首元结点)
float date; // 此处数据类型可自己定义,可用结构体等 *num或num[]都可
}*List, Node;

// 单链表的初始化 (带有头结点) (循环链表的最后一个结点指向头节点)
// 带有尾指针的循环链表
int initList(List &l){
l->next = NULL;
return OK;
}

// 判断链表是否为空
int isEmpty(List &l){
return l->next==NULL?TRUE:FALSE;
}

// 销毁单链表
int destroyList(List &l){
Node *node = l;
while(node){
l = node;
node = node->next;
delete l;
}
return OK;
}

// 清空单链表(可以尝试递归删除)
int clearList(List &l){
Node *node = l->next;
destroyList(node);
l->next = NULL;
return OK;
}

// 求表长
int getLength(List &l){
Node* node = l->next;
int i = 0;
while(node){
i++;
node = node->next;
}
return i;
}

// 获取某个元素的内容
int getElem(List &l, int n){
Node *node = l->next;
int i = 1;
while(i node = node->next;
++i;
}
if(i>n||!node->date) return ERROR;
return node->date;
}

// 定位元素位置
int locateElem(List &l, float elem){
Node *node = l->next;
int i = 1;
for(;node&&node->date!=elem;++i){
node = node->next;
}
if(node) return i;
return ERROR;
}

// 插入元素
int insertElem(List &l, float elem, int n){
Node *node = new Node;
Node *p = l->next;
int i = 1;
while(i i++;
p = p->next;
}
if(i>=n||!p) return ERROR;
node->date = elem;
node->next = p->next;
p->next = node;
return OK;
}

// 删除元素并返回删除元素得值
int deleteElem(List &l, int n){
Node *h = new Node;
Node *p = l->next;
int i = 1;
float e;
while(i i++;
p = p->next;
}
if(i>=n||!p) return ERROR;
h = p->next;
e = h->date;
p->next = p->next->next;
delete h;
return e;
}

// 创建一个链表(头插法)
List createList(int n){
List l = new Node;
l->next = NULL;
for(int i=0;i Node node = new Node;
node->next = l->next;
node->date = i
2;
l->next = node;
}
return l;
}

// 尾插法
List createList_R(int n){
List l = new Node;
Node *p = l;
l->next = NULL;
for(int i=0;i Node node = new Node;
node->next = NULL;
node->date = i
2;
p->next = node;
p = node;
}
return l;
}

int main(void){
List l = new Node;
// cout << l->next;
// cout << isEmpty(l);
// initList(l);
// cout << l->head;
return 1;
}

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/768422.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号