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

数据结构 ------单链表的基本实现

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

数据结构 ------单链表的基本实现

带头结点的单链表基本操作实现

#include 
#include 

typedef struct _node {
	int val;
	struct _node *next;
} Node;

typedef struct _list {
	Node *pHead;
	int length;
} List;

void InitList(List *list);//初始化链表
void ClearList(List *pList);//清空链表
int ListEmpty(List list);//链表判空
int ListLength(List list);//返回链表长度
void GetElem(List list, int i, int *e);//根据位置返回值
Node *LocateElem(List list, int e);//根据值返回指向该节点的指针
void ListInsert(List *list, int i, int e);//在位置i上插入值为e的结点
void Delete(List *pList, int i, int *e);//删除位置i上的结点,并用e返回结点值。

int main() {
	int x;
	List list;
	InitList(&list);

//	Node *node = (Node *)malloc(sizeof(Node));
//	node->val = 3;
//	node->next = NULL;
//	list.pHead->next = node;
	printf("%dn", ListLength(list));
	ListInsert(&list, 1, 3);
	Delete(&list, 1, &x);
	printf("%d %d", ListLength(list), x);

	return 0;
}

void InitList(List *pList) {
	Node *node = (Node *)malloc(sizeof(Node));
	node->val = 0;
	node->next = NULL;
	pList->pHead = node;
}

void ClearList(List *pList) {
	Node *node = pList->pHead->next;
	if (node) {
		while (node->next) {
			Node *temp = node;
			node = node->next;
			free(temp);
		}
	}
	pList->pHead->next = NULL;
}

int ListEmpty(List list) {
	if (list.pHead->next == NULL)
		return 1;
	return 0;
}

int ListLength(List list) {
	int len = 0;
	Node *node = list.pHead;
	if (ListEmpty(list))
		return 0;
	while (node->next) {
		len++;
		node = node->next;
	}
	return len;
}

void GetElem(List list, int i, int *e) {
	if (ListEmpty(list) || i < 1 || i > ListLength(list))
		return;
	int count = 0;
	Node *node = list.pHead;
	while (count != i) {
		node = node->next;
		count++;
	}
	*e = node->val;
}

Node *LocateElem(List list, int e) {
	Node *ret = list.pHead;
	if (ListEmpty(list))
		return NULL;
	while (ret) {
		if (ret->val == e)
			return ret;
		ret = ret->next;
	}
	return NULL;
}

void ListInsert(List *list, int i, int e) {
	int j = 0;
	Node *p = list->pHead;
	if (i < 1 || i > ListLength(*list) + 1)
		return;
	while (j < i - 1) {
		j++;
		p = p->next;
	}
	Node *node = (Node *)malloc(sizeof(Node));
	node->val = e;
	node->next = p->next;
	p->next = node;
}

void Delete(List *pList, int i, int *e) {
	int j = 0;
	Node *p, *q;
	p = pList->pHead;
	if (i < 1 || i > ListLength(*pList))
		return;
	while (j < i - 1) {
		p = p->next;
		j++;
	}
	q = p->next;
	p->next = p->next->next;
	*e = q->val;
	free(q);
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/968431.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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