C语言 双向循环链表 其中包括:初始化,头插,尾插,头删,尾删,查询...


一、代码描述

C语言 双向循环链表 其中包括:初始化,头插,尾插,头删,尾删,查询…


二、参考代码

#include<stdio.h>
#include<stdlib.h>
#include<assert.h>
//双向循环链表 
typedef int LTDataType;

typedef struct ListNode
{
	LTDataType data;
	struct ListNode* next;
	struct ListNode* pre;
	
}ListNode;

ListNode* ListInit() {
	ListNode* phead = (ListNode*)malloc(sizeof(ListNode));
	phead->next = phead;
	phead->pre = phead;
	return phead;
}

ListNode* ListFind(ListNode* phead, LTDataType x) {
	assert(phead);

	printf("查找\n");
	ListNode* cur = phead->next;
	while (cur != phead) {
		if (cur->data == x) {
			return cur;
		}
		cur = cur->next;
	}
	return NULL;
	
}

void ListPushBack(ListNode* phead, LTDataType x) {
	assert(phead);

	ListNode* tail = phead->pre;
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	newnode->data = x;
	//Link to
	tail->next = newnode;
	newnode->pre = tail;
	newnode->next = phead;
	phead->pre = newnode;
}

void ListPri(ListNode* phead)
{
	assert(phead);

	ListNode* cur = phead->next;
	while (cur != phead) {
		printf("%d ", cur->data);
		cur = cur->next;
	}
	printf("\n");
}

void ListPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);

	ListNode* tail = phead->next;
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	newnode->data = x;

	//Link to
	newnode->pre = phead;
	newnode->next = tail;
	phead->next = newnode;
	tail->pre = newnode;
}

void ListPopBack(ListNode* phead)
{
	printf("尾删\n");
	assert(phead);
	assert(phead->next != phead);
	ListNode* tail = phead->pre;
	ListNode* tailpre = tail->pre;
	tailpre->next = phead;
	phead->pre = tail;

	free(tail);
}

void ListInsert(ListNode* pos, LTDataType x) {
	assert(pos);

	printf("插入\n");
	ListNode* PosPre = pos->pre;
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	newnode->data = x;

	//posPre newnode pos
	PosPre->next = newnode;
	newnode->next = pos;
	pos->pre = newnode;
	newnode->pre = PosPre;
}

void ListErase(ListNode* pos) {
	assert(pos);
	//......
}

void ListPopFront(ListNode* phead)
{
	printf("头删\n");
	assert(phead);
	assert(phead->next != phead);
	
	ListNode* cur = phead->next;
	phead->next = cur->next;
	cur->pre = phead;

	free(cur);
}

void Test()
{
	ListNode* plist = ListInit();
	printf("尾插\n");
	ListPushBack(plist, 1);
	ListPushBack(plist, 2);
	ListPushBack(plist, 3);
	ListPushBack(plist, 4);
	ListPri(plist);

	ListPopBack(plist);
	ListPri(plist);

	printf("头插\n");
	ListPushFront(plist, 0);
	ListPri(plist);

	ListPopFront(plist);
	ListPri(plist);
}
int main() {

	Test();
	return 0;
}


  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Z1Jxxx

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值