C语言--实现双向链表(头插法)

详细解释已经在代码注释中

#include<stdio.h>
#include "malloc.h"

//结构体
struct MyStruct
{
	int data;
	MyStruct* start;//前驱指针
	MyStruct* next;//下一个节点指针

};
//双向链表的实现(头插法)
MyStruct* getDoubleLink() {
	MyStruct* head = NULL;//头指针
	//创建头节点
	MyStruct* t = (MyStruct*)malloc(sizeof(MyStruct));//分配内存空间
	t->next = NULL;//前驱指针为空
	t->start = NULL;//后节点为空
	head = t;//指向头节点
	return head;
}
//向获取到的链表添加数据的函数
bool addData(MyStruct* head) {
	
	if (head != NULL) {
		
		if (head->next != NULL) {
			int data = 0;
			scanf("%d", &data);
			MyStruct* t = (MyStruct*)malloc(sizeof(MyStruct));//分配内存空间
			t->data = data;//赋值
			t->start = head;//新节点前驱指向头节点
			t->next = head->next;//新节点后驱指针指向第二节点
			head->next->start = t;//第二节点的前驱节点指向新节点
			head->next = t;//头节点指向新节点
			return true;
		}
		//插入第一个节点时
		else{
			int data = 0;
			scanf("%d", &data);
			MyStruct* t = (MyStruct*)malloc(sizeof(MyStruct));//分配内存空间
			t->data = data;//赋值
			t->next = NULL;//后指针置空
			t->start = head;//指向头节点
			head->next = t;//头节点指向第二节点
		}
	}
	else
	{
		return false;
	}
}
int main() {
	//获取双向链表
	MyStruct* head=getDoubleLink();
	//添加数据
	addData(head);
	addData(head);
	addData(head);
	MyStruct* t = head->next;
	//遍历双向链表
	for (;;) {
		printf("%d\n", t->data);
		if (t->next == NULL)
			break;
		t = t->next;
		
	}

	return 0;
}

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

孔雀南飞梦

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

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

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

打赏作者

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

抵扣说明:

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

余额充值