C语言小知识 --- 数据结构 ---双向链表

啦,双向链表应该是长这个样子的:

C语言小知识 --- 数据结构 ---双向链表_第1张图片 双向链表

接下来丢代码了,嘻嘻 :

#include 
#include 

typedef struct My_list
{
	int data;
	struct My_list * Next;//下一个
	struct My_list * Prev;//上一个

}M_L, * P_M_L;


P_M_L Create_Node()
{
	P_M_L node = (P_M_L)malloc(sizeof(M_L));
	if(node == NULL) return NULL;

	node->Next = NULL;
	node->Prev = NULL;

	return node;
}


int Add_Node(P_M_L Head)
{
	if(Head == NULL) return -1;

	P_M_L add_node = Create_Node();//创建一个要添加的结点
	if(add_node == NULL)return -1;

	printf("请输入要添加的数据:");
	scanf("%d",&add_node->data);

	P_M_L new_node = Head;//定义一个存放头节点的地址,保证头节点的稳定性

	while(new_node->Next != NULL)
		new_node = new_node->Next;


	new_node->Next = add_node;
	add_node->Prev = new_node;

	return 0;
}


int Display_List(P_M_L Head)
{
	if(Head == NULL || Head ->Next == NULL) return -1;

	P_M_L new_node = Head;

	while(new_node->Next != NULL)
	{
		new_node = new_node->Next;
		printf("%d\n",new_node->data);
	}

	return 0;
}


P_M_L Find_Node(P_M_L Head,int find_data)
{
	if(Head == NULL || Head->Next == NULL) return NULL;

	P_M_L new_node = Head;

	while(new_node->Next != NULL)
	{
		new_node = new_node->Next;
		if(new_node->data == find_data)
			return new_node;
	}

	return NULL;
}


int Del_Node(P_M_L Head)
{
	if(Head == NULL || Head->Next == NULL) return -1;

	P_M_L new_node = Head;
	int del_data;
	printf("请输入要删除的数据:");
	scanf("%d",&del_data);

	P_M_L del_node = Find_Node(Head,del_data);
	if(del_node == NULL) return -1;


	while(new_node->Next != NULL)//这个hile是获取删除结点的上一个节点
	{
		if(new_node->Next == del_node)break;
		new_node = new_node->Next;
	}



	if(del_node->Next == NULL)//判断要删除的结点是不是最有一个结点
	{
		new_node->Next = NULL;
		del_node->Prev = NULL;

	}
	else
	{
        new_node->Next = del_node->Next;
        del_node->Next->Prev = new_node;

        del_node->Next = NULL;
        del_node->Prev = NULL;
	}

	return 0;
}


int main()
{
	P_M_L Head = Create_Node();
	if(Head == NULL)  printf("创建结点失败 ! \n");

	int add_ret = Add_Node(Head);
	if(add_ret == -1) printf("添加数据失败 !\n");
	add_ret = Add_Node(Head);
	add_ret = Add_Node(Head);
	add_ret = Add_Node(Head);


	int dis_ret = Display_List(Head);
	if(dis_ret == -1)printf("显示链表数据失败 !\n");

	int del_ret = Del_Node(Head);
	if(del_ret == -1)printf("删除失败 ! \n");

	Display_List(Head);

	return 0;
}

 

 

你可能感兴趣的:(Simple-C)