欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数据结构——双向链表的创建、插入、删除

程序员文章站 2022-03-22 19:52:27
...

 

#include "iostream"
using namespace std;
typedef struct DuLNode{
	int data;
	struct DuLNode *prior;
	struct DuLNode *next;
}DuLNode,*DuLinkList;
void CreateDuLinkList(DuLinkList&L,int n);
void ShowDuLinkList(DuLinkList&L);
void InsertDuLinkList(DuLinkList&L,int element,int location);
void DeleteDuLinkList(DuLinkList&L,int location,int&element);
void main(){
	DuLinkList L;
	CreateDuLinkList(L,5);
	ShowDuLinkList(L);
	InsertDuLinkList(L,100,3);
	ShowDuLinkList(L);
	int element;
	DeleteDuLinkList(L,3,element);
	ShowDuLinkList(L);
}
void CreateDuLinkList(DuLinkList&L,int n){
	L = (DuLinkList)malloc(sizeof(DuLNode));
	DuLinkList slide = L;
	int len = 0;
	for (int i = 0;i<n;i++)
	{

		DuLinkList p = (DuLinkList)malloc(sizeof(DuLNode));
		p->data = i;
		slide->next = p;
		p->prior = slide;
		slide = p;
		len++;
	}
	slide->next = L;
	L->data = len;//头结点中的数据域保存链表的长度

}
void ShowDuLinkList(DuLinkList&L){
	DuLinkList slide = L->next;
	//头结点中的数据域保存链表的长度,可以采用这种方式
	for (int i = 0;i<L->data;i++)
	{
		cout<<slide->data<<endl;
		slide = slide->next;
	}
	////任意链表均可以采用这种形式
	//while(slide!=L){
	//	cout<<slide->data<<endl;
	//	slide = slide->next;
	//}
	cout<<"---------------------"<<endl;
}
void InsertDuLinkList(DuLinkList&L,int element,int location){
	//扫描定位
	// 1<=location<=len+i
	DuLinkList slide = L;
	int loc = 1;
	while(slide&&loc<=location){
		slide = slide->next;
		loc++;
	}
	if (location>1&&slide!=L)
	{

		DuLinkList p = (DuLinkList)malloc(sizeof(DuLNode));
		p->data = element;
		p->prior = slide->prior;
		slide->prior->next = p;
		slide->prior = p;
		p->next = slide;
	}
}
void DeleteDuLinkList(DuLinkList&L,int location,int&element){
	//扫描定位
	// 1<=location<=len+i
	DuLinkList slide = L;
	int loc = 1;
	while(slide&&loc<=location){
		slide = slide->next;
		loc++;
	}
	if (slide!=L)
	{
		element = slide->data;
		slide->prior->next = slide->next;
		slide->next->prior = slide->prior;
		free(slide);

	}


}