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

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

#include
#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;
}

你可能感兴趣的:(笔记,链表,c语言,数据结构)