双链表相关操作

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

typedef struct DLnode
{
	int data;
	struct DLnode *prior, *next;
}DLnode, *DLinkList;

/*初始化双链表*/
void Init_DLinkList(DLinkList &L)
{
	L = (DLnode*)malloc(sizeof(DLnode));    //初始化头结点
	L->prior = L->next = NULL;    //初始化头尾指针
}

/*在双链表L的第i个元素前面插入值为 x的新节点*/
void Inser_DLinkList(DLinkList &L, int i, int x)
{
	int j = 0;
	DLinkList p = L, s;
	while(p != NULL && j < i)
	{
		j++;
		p = p->next;
	}
	if(p == NULL)
	{
		printf("第j个节点不存在\n");
	}
	else
	{
		s = (DLnode*)malloc(sizeof(DLnode));
		s->data = x;
		s->prior = p->prior;
		s->next = p;
		p->prior->next = s;
		p->prior = s;
	}
}

/*删除第i个数据元素*/
void Delete_DLinkList(DLinkList &L, int i)
{
	int j = 0;
	DLinkList p = L;
	while(p != NULL && j < i)
	{
		j++;
		p = p->next;
	}
	if(p == NULL)
	{
		printf("第j个节点不存在\n");
	}
	else
	{
		p->prior->next = p->next;
		if(p->next != NULL)
		{
			p->next->prior = p->prior;
		}
	    free(p);
	}

}

/*打印双链表*/
void Print_DLinkList(DLinkList &L)
{	
	DLnode* p;
	p = L->next;		//L是头指针,p指向第一个节点,开始打印
	while(p != NULL)
	{
		printf("%d\n", p->data);
		p = p->next;
	}
}

int main()
{
	DLinkList L;
	Init_DLinkList(L);
	DLnode *L1 = (DLnode*)malloc(sizeof(DLnode));
	L1->data = 1;
	L->next = L1;
	L1->prior = L;
	L1->next = NULL;

	printf("初始化一个节点,双链表是\n");
    Print_DLinkList(L);
	
	printf("插入元素后,双链表是\n");
	Inser_DLinkList(L, 1, 4);
	Inser_DLinkList(L, 2, 5);
	Print_DLinkList(L);

	printf("删除元素后,双链表是\n");
	Delete_DLinkList(L, 2);
	Print_DLinkList(L);

	return 0;
}

你可能感兴趣的:(struct,null,delete,include)