目录
1.双向链表的基本操作
#include <iostream>
using namespace std;
typedef int Elemtype;
typedef struct LinkNode {
Elemtype data;
LinkNode *next, *previous;
} * DLIST, *Node;
void Delete(Node p)
{ //删除p结点
if (p->previous != NULL) {
p->previous->next = p->next;
}
if (p->next != NULL) {
p->next->previous = p->previous;
}
delete p;
}
void MakeNull(DLIST &DL)
{ // 将双向链表置空
delete DL->next;
DL = new LinkNode;
DL->next = NULL;
DL->previous = NULL;
}
void Insert(Elemtype x, Node p)
{ //在结点p后添加结点q
Node q = new LinkNode;
q->data = x;
q->next = p->next;
p->next->previous = q;
p->next = q;
q->previous = p;
}
Node Locate(Elemtype x, DLIST DL)
{ //定位第一个值为x的元素
Node p = DL;
while (p->next != NULL) {
if (p->next->data == x)
return p->next;
else
p = p->next;
}
return p->next;
}
2.双向链表的创建和打印
void CreatDList(DLIST &DL, int n)
{
int x;
Node p = DL;
p->previous = NULL;
p->next = new LinkNode;
p->next->next = NULL;
for (int i = 0; i < n; i++) {
cin >> x;
Insert(x, p);
}
}
void PrintDList(DLIST DL)
{
Node p = DL;
while (p->next != NULL) {
cout << p->next->data << "\t";
p = p->next;
}
cout << endl;
}
3.指定值为x的结点与其前驱结点交换
int Swap(Elemtype x, DLIST &DL)
{ //若链表中存在元素值为x的结点,将其与其前驱结点进行交换
Node p1, p2;
p1 = Locate(x, DL);
if (p1 == NULL)
return 0;
else {
Insert(x, p1->previous->previous);
Delete(p1); //先将新x插入前驱结点的前面,再删除旧x
return 1;
}
}
int main()
{
DLIST DL = new LinkNode;
cout << "输入5个数据创建双向链表: ";
CreatDList(DL, 5);
PrintDList(DL);
Swap(2, DL);
PrintDList(DL);
}