/*
實現雙向鏈表。
*/
#include<iostream>
typedef int ElemType;
typedef struct DuLnode {
ElemType data;
struct DuLnode* prior, * next;
}DuLnode, *DuLinklist;
bool InitList_L(DuLinklist& L) {
/*
初始化雙向列表。
*/
L = new DuLnode;
if (!L)
return false;
L->prior = NULL;
L->next = NULL;
return true;
}
bool CreateDuList_H(DuLinklist& L) {
/*
頭插法創建雙向鏈表。
*/
int n;
DuLinklist s;
std::cout << "請輸入您要插入元素的個數" << std::endl;
std::cin >> n;
std::cout << "請以此輸入您要插入的元素" << std::endl;
std::cout << "頭插法創建鏈表...." << std::endl;
while (n--) {
s = new DuLnode;
if (!s)
return false;
std::cin >> s->data;
s->next = L->next;
s->prior = L;
if(L->next)
L->next->prior = s;
L->next = s;
}
return true;
}
bool GetElem(DuLinklist L, int i, int& e) {
/*
雙向鏈表取值;
*/
DuLinklist p;
p = L->next;
for (int j = 0; j < i - 1; j++) {
if (!p)
return false;
p = p->next;
}
e = p->data;
return false;
}
int LocateElem(DuLinklist L, int e) {
/*
在雙向列表中查找元素。
*/
DuLinklist p;
p = L->next;
int j = 1;
while (p && p->data != e) {
p = p->next;
j++;
}
if (!p)
return 0;
return j;
}
bool Print_DuList(DuLinklist L) {
DuLinklist p;
p = L->next;
if (!p)
return false;
while (p) {
std::cout << p->data << " ";
p = p->next;
}
std::cout << std::endl;
return true;
}
bool ListInsert_L(DuLinklist& L, int i, int& e) {
/*
在雙向鏈表的第i個位置插入元素e;
*/
DuLinklist p, s;
p = L->next;
int j = 0;
while (p && j++ < i) {
p = p->next;
}
if (!p || j > i)
return false;
s = new DuLnode;
s->data = e;
p->prior->next = s;
s->prior = p->prior;
s->next = p;
p->prior = s;
return true;
}
bool ListDelete_L(DuLinklist& L, int i) {
/*
雙向鏈表之刪除元素。
*/
DuLinklist p;
p = L->next;
int j = 0;
while (p && j < i-1) {
p = p->next;
j++;
}
if (!p || j > i)
return false;
if(p->next)
p->next->prior = p->prior;
p->prior->next = p->next;
delete p;
return true;
}
int main() {
DuLinklist L;
InitList_L(L);
CreateDuList_H(L);
Print_DuList(L);
//int i, e;
//std::cout << "請輸入您要取得數的位置" << std::endl;
//std::cin >> i;
//GetElem(L, i, e);
//std::cout << "您所取得數爲:" << e << std::endl;
//Print_DuList(L);
//int e, i;
//std::cout << "請您輸入你要查找的元素" << std::endl;
//std::cin >> e;
//i = LocateElem(L, e);
//std::cout << "您所查找的元素位於" << i << "位置" << std::endl;
//int i, e;
//std::cout << "請輸入您要插入的元素的位置" << std::endl;
//std::cin >> i;
//std::cout << "請輸入您要插入的元素" << std::endl;
//std::cin >> e;
//ListInsert_L(L, i, e);
int i;
std::cout << "請輸入您要刪除元素的位置" << std::endl;
std::cin >> i;
ListDelete_L(L, i);
Print_DuList(L);
return true;
}