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

C语言实现链表常用接口(双向带头循环链表)

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

C语言实现链表常用接口(双向带头循环链表)

文章目录
  • 定义节点
  • 初始化链表
  • 创建节点
  • 尾插
  • 头插
  • 尾删
  • 头删
  • 查找节点
  • 后插
  • 前插
  • 删除任意位置节点
  • 打印链表所有节点
  • 销毁链表


定义节点
typedef int dataType;
typedef struct ListNode ListNode;
struct ListNode
{
	ListNode* prev;
	dataType data;
	ListNode* next;
};

初始化链表
void initList(ListNode* head)
{
	head->next = head;
	head->prev = head;
}

创建节点
ListNode* createNode(dataType x)
{
	ListNode* node = malloc(sizeof (ListNode));
	node->data = x;
	return node;
}

尾插
void listPushBack(ListNode* head, dataType x)
{
	assert(head != NULL);
	ListNode* tail = head->prev;
	ListNode* node = createNode(x);
	tail->next = node;
	node->prev = tail;
	node->next = head;
	head->prev = node;	
}

头插
void listPushFront(ListNode* head, dataType x)
{
	assert(head != NULL);
	ListNode* first = head->next;
	ListNode* node = createNode(x);
	head->next = node;
	node->prev = head;
	node->next = first;
	first->prev = node;
}

尾删
void listPopBack(ListNode* head)
{
	assert(head->next != NULL);
	ListNode* tail = head->prev;
	ListNode* tailPrev = tail->prev;
	tailPrev->next = head;
	head->prev = tailPrev;
	free(tail);
}

头删
void listPopFront(ListNode* head)
{
	assert(head->next != NULL);
	ListNode* first = head->next;
	ListNode* second = first->next;
	head->next = second;
	second->prev = head;
	free(first);
}

查找节点
ListNode* findNode(ListNode* head, dataType x)
{
	ListNode* cur = head->next;
	while (cur != head)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

后插
void listInsertAfter(ListNode* pos, dataType x)
{
	assert(pos != NULL);
	ListNode* next = pos->next;
	ListNode* node = createNode(x);
	pos->next = node;
	node->prev = pos;
	node->next = next;
	next->prev = node;
}

前插
void listInsertBefore(ListNode* pos, dataType x)
{
	assert(pos != NULL);
	ListNode* prev = pos->prev;
	ListNode* node = createNode(x);
	prev->next = node;
	node->prev = prev;
	node->next = pos;
	pos->prev = node;
}

删除任意位置节点
void listErase(ListNode* pos)
{
	assert(pos != NULL);
	assert(pos != head);
	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
}

打印链表所有节点
void printList(ListNode* head)
{
	ListNode* cur = head->next;
	while (cur != head)
	{
		printf("%d->", cur->data);
		cur = cur->next;
	}
	printf("NULLn");
}

销毁链表
void destroyList(ListNode* head)
{
	ListNode* cur = head->next;
	while (cur != head)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(head);
}
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1002122.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

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

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