双向链表插入与删除

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

typedef struct node
{
	int data;
	struct node *pre;
	struct node *next;
}dnode;

/*
	双向链表删除结点
*/
dnode *Del_Node(dnode *Head, int num)
{
	dnode *p1,*p2;
	p1 = Head;
	
	// 遍历到num结点
	while( num != p1->data && p1->next != NULL)
	{
		p1 = p1->next;
	}
	// 找到了数据域为data的结点
	if(num == p1->data)
	{
		if( p1 == Head )			// 要删除的结点是头结点 
		{
			Head = Head->next;		// 更新头结点位置及其指针域
			Head->pre = NULL;
			free(p1);
		}
		else if(p1->next == NULL)	// 要删除的是最后一个结点
		{
			p1->pre->next = NULL;
			free(p1);
		}
		else						// 中间结点
		{
			p1->next->pre = p1->pre;
			p1->pre->next = p1->next;
			free(p1);
		}
	}
	else
	{
		printf("%d cound not been found",num);
		
	}	
	return Head;
}

/*
	双向链表插入结点
*/
dnode *Insert_Sort(dnode *Head, int num)
{
	dnode *p0,*p1;
	p1 = Head;
	p0 = (dnode *)malloc( sizeof(dnode) );
	p0->next = NULL;
	p0->pre  = NULL;
	p0->data = num;
	
	if(p1 == NULL)
	{
		Head = p0;	
		return Head;
	}
	
	// 遍历
	while( (p0->data > p1->data) && (p1->next != NULL) )
	{
		p1 = p1->next;
	}
	
	if(p0->data <= p1->data)
	{
		if(Head == p1)			// 头结点
		{
			p0->next = p1;
			p1->pre  = p0;
			Head = p0;
		}
		else 
		{
			p1->pre->next = p0;
			p0->next      = p1;
			p0->pre       = p1->pre;
			p1->pre       = p0;
		}
	}
	else						// 最后一个结点
	{
		p1->next = p0;
		p0->pre  = p1;
		p0->next = NULL;
	}
	
	
	return Head;
}

/* print list item->name */
void print_list(dnode *Head)
{
	dnode *temp = Head;

	while(temp)
	{
		printf("-------- %d\n",temp->data);
		temp = temp->next;
	}	
}

void main()
{
	dnode *Head = NULL;
	int i = 0;
	
	while( i++ < 10 )
	{
		Head = Insert_Sort(Head,i);		
	}
	
	print_list(Head);
	
	printf("------------------------------\n");
	
	Head = Del_Node(Head,1);
	Head = Del_Node(Head,5);
	Head = Del_Node(Head,10);
	
	print_list(Head);

}

相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页