双向链表基本操作代码

/*
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

						   ⚝ 学习不入神,子枫嫁别人 ⚝

   Author: ChenFeng

   Time: 2020年07月17日 08:14:19
   
   Describe $Used to do something$

						   ⚝ 认真小阿晨,子枫娶进门 ⚝

 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 */               

#include 
#include 
#include 

typedef int Elemtype;

typedef struct DNode{
	Elemtype data;
	struct DNode *prior, * next;
}DNode,*Dlinklist;

//DNode* GetElem(Dlinklist& L, int i);



//创建双向链表
/* 
基本代码感觉和单链表没有什么区别,就是一个前驱指针的区别

TIME:2020年07月17日 11:18:13  
问题:尾插法为什么是在p节点上操作,而不是L节点上,这样L链表上不是没有数据吗?

之前参考的代码写错了,p要定义成一个指针,它后面步骤是将p指针向后移动
*/
void Creat_TailDlinklist(Dlinklist &L) {
	L = new DNode;
	DNode* s,* p=L;
	//L = (DNode*)malloc(sizeof(DNode)); //头节点
	p->next = NULL;
	Elemtype x;
	scanf_s("%d", &x);
	while (x!=-1)
	{
		//p = (DNode*)malloc(sizeof(DNode));
		s = new DNode;
		s->data = x;
		s->next = NULL;
		s->prior = p;
		p->next = s;
		p = s;
		//L->next->prior = p;
		scanf_s("%d", &x);
	}
}

//头插法建立双向链表
void Creat_HeadDlinklist(Dlinklist &L) {
	int x;
	L = new DNode;
	DNode* s, * p = L;
	L->next = L->prior = NULL;
	scanf_s("%d", &x);
	while (x != -1) {
		s = new DNode;
		s->data = x;
		s->next = L->next;
		s->prior = L;
		if(L->next)
			L->next->prior = s;
		L->next = s;
		scanf_s("%d", &x);
	}
}


//输出双链表,也可以修改为计算表长
void Print_Dlinklist(Dlinklist L) {
	DNode* p;
	p = L->next;
	while (p) {
		printf("%d ", p->data);
		p = p->next;
	}	
}


//按序号查找操作
DNode*  GetElem(Dlinklist L, int i) {
	int j = 1;
	DNode* p = L->next;
	if (i == 0)
		return L;
	if (i <= 0)
		return NULL;
	while (p && j < i) {
		p = p->next;
		j++;
	}
	//printf_s("%d",p->data
	return p;
}

//按值查找操作

DNode* LocateElem(Dlinklist L,int e) {
	DNode* p = L->next;
	while (p != NULL && p->data != e)
		p = p->next;
	return p;
}


//双向链表的插入操作,在第i个位置之前插入一个节点
int Insert_Dlinklist(Dlinklist& L, int i) {
	DNode* p, * s;
	int x;
	if (!(p = GetElem(L, i)))
		return -1;
	if (!(s = (Dlinklist)malloc(sizeof(DNode))))
		return -1;
	/*getchar();
	fflush(stdin);*/
	printf_s("请输入插入的值:");
	scanf_s("%d", &x);
	s->data = x;
	s->prior = p->prior;
	p->prior->next = s;
	p->prior = s;
	s->next = p;
	return 0;
}

//双向链表的删除操作
int Delete_Dlinklist(Dlinklist & L,int i) {
	DNode* p, * s;
	int x;
	if (!(p = GetElem(L, i)))
		return -1;
	x = p->data;
	/*if (!(s = (Dlinklist)malloc(sizeof(DNode))))
		return -1;*/
	p->next->prior = p->prior;
	p->prior->next = p->next;
	free(p);
	return 0;
}


int main()
{
	Dlinklist L;
	Creat_HeadDlinklist(L);
	Print_Dlinklist(L);
	GetElem(L, 2);
	Insert_Dlinklist(L, 1);
	Print_Dlinklist(L);
	Delete_Dlinklist(L, 1);
	Print_Dlinklist(L);
}

 

你可能感兴趣的:(数据结构)