关于双链表的相关操作

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct node 
{
	int data;
	struct node *next;
	struct node *prev;
};

struct node *create_node(int num)
{
	struct node *p = (struct node*)malloc(sizeof(struct node));

	if(p == NULL)
	{
		printf("error");
		return NULL;
	}
	bzero(p,sizeof(struct node));
	p->data = num;
	p->prev = NULL;
	p->next = NULL;

	return p;
}
void insert_tail(struct node *head,struct node *new)
{
	struct node *p = head;
	while(p->next != NULL)
	{
		p = p->next;
	}
	p->next = new;
	new->next = NULL;
	new->prev = p;

}

void insert_head(struct node *head,struct node *new)
{
	new->next = head->next;

	if(head->next != NULL)
	{
		head->next->prev = new;
	}
	head->next = new;
	new->prev = head;
//	head->next->prev = new;
}

void insert_middle(struct node *head,struct node *new,int num)
{
	int flag = 0;
	struct node *p = head;
	struct node *temp = NULL;

	while(p->next != NULL)
	{
		p = p->next;
		temp = (struct node*)malloc(sizeof(struct node));
		temp->data = new->data;
		if(p->data == num)
		{
			if(p->next == NULL)
			{
				p->next = new;
				new->prev = p;
				new->next = NULL;
				flag = 1;
			}
			else
			{
				temp->next = p->next;
				p->next->prev = temp;
				p->next = temp;
				temp->prev = p;
				p = p->next;
				free(temp);
				temp = NULL;
				flag = 1;
			}
		}
	}
	
	if(flag == 0)
	{
		printf("NO find! insert error!\n");

	}
}
#if 1
int  delete_node(struct node *head,int num)
{
	struct node *p = head;
	struct node *ptr = NULL;
	while(p->next != NULL)
	{
		ptr = p;
		p = p->next;
		if(p->data == num)
		{
			if(p->next == NULL)
			{
				ptr->next = NULL;
				free(p);
				p = NULL;
			}
			else
			{
				ptr->next = p->next;
				p->next->prev = ptr;
				free(p);
				p = NULL;
			}
			return 0;
		}
	}
}
#endif
struct node *display(struct node *head)
{
	struct node *p = head;
	while(p->next != NULL)
	{
		p = p->next;
		printf("%d\n",p->data);
	}
	return p;
}

void display_tail(struct node *p)
{
	while(p->prev != NULL)
	{
		printf("%d\n",p->data);
		p = p->prev;
	}
}
int main()
{
	struct node *head = create_node(0);
	int i = 0;
	struct node *ptr = (struct node*)malloc(sizeof(struct node));

	for(i = 0;i < 5;i++)
	{
		struct node *new = (struct node *)malloc(sizeof(struct node));
		new->data = i+1;
	//	insert_tail(head,new);
		insert_head(head,new);
	}
	struct node *new = (struct node*)malloc(sizeof(struct node));
	new->data = 3;
	insert_head(head,new);

	ptr = display(head);

	printf("前向遍历:\n");
	display_tail(ptr);
	printf("中间插入:\n");
	new = (struct node *)malloc(sizeof(struct node));
	new->data = 18;
	insert_middle(head,new,3);
	display(head);
	printf("删除结点:\n");
	delete_node(head,4);
	display(head);
	printf("再次前序遍历:\n");
	display_tail(ptr);
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值