#include"iostream"
#include"stdlib.h"
using namespace std;
typedef struct DNode {
int data;
struct DNode *prior;
struct DNode *next;
}DNode,*DLinklist;
bool Init(DLinklist &L) {
DNode* p = (DNode*)malloc(sizeof(DNode));
if (p == NULL)
return false;
p->prior = NULL;
p->next = NULL;
L = p;
return true;
}
DLinklist insert_head(DLinklist& L,int e) {
DNode *p = (DNode*)malloc(sizeof(DNode));
if (p == NULL)
return NULL;
p->data = e;
if (L->next == NULL)
{
L->next = p;
p->prior = L;
p->next = NULL;
return L;
}else{
p->next = L->next;
L->next->prior = p;
p->prior = L;
L->next = p;
}
return L;
}
DNode* GetElem(DLinklist L, int i) {
if (i < 1) return NULL;
DNode *p = L->next;
int j = 1;
if (p == NULL)
return NULL;
while (p != NULL && j < i) {
p = p->next;
j++;
}
return p;
}
bool Insert(DLinklist &L,int i,int e) {
if (i < 1)
return false;
DNode *p = GetElem(L, i);
if (p == NULL)
return false;
DNode *New = (DNode*)malloc(sizeof(DNode));
New->data = e;
if (p->next == NULL) {
New->prior = p;
p->next = New;
New->next = NULL;
return true;
}
New->next = p->next;
p->next->prior = New;
New->prior = p;
p->next = New;
return true;
}
bool Delete(DLinklist &L,int i) {
if (i < 1)
return false;
DNode *p = GetElem(L, i);
if (p == NULL)
return false;
DNode* p_prior=p->prior;
DNode* p_next=p->next;
if (p_next != NULL)
{
p_next->prior = p_prior;
}
p_prior->next = p_next;
free(p);
return true;
}
bool DestoryDinkList(DLinklist &L) {
DNode *p = L->next;
if (p == NULL)
return true;
while (p->next!= NULL) {
p->next->prior = L;
L->next = p->next;
free(p);
p = L->next;
}
free(p);
L->next = NULL;
return true;
}
void Print_DLinklist(DLinklist L) {
int n = 0;
DNode *p = L->next;
while (p != NULL) {
cout << p->data << " ";
n++;
p = p->next;
}
cout << endl;
cout << "当前链表长度:" << n<<endl;
}
int main(){
DLinklist L;
Init(L);
Print_DLinklist(L);
for (int i = 1; i <= 10; i++)
insert_head(L, i);
Print_DLinklist(L);
DNode* res=GetElem(L, 110);
if (res != NULL)
cout << "查找结果为:" << res->data << endl;
else
cout << "查找结果为:NULL" << endl;
Insert(L, 10, 999);
Print_DLinklist(L);
Delete(L, 11);
Print_DLinklist(L);
DestoryDinkList(L);
Print_DLinklist(L);
system("pause");
return 0;
}