假设在长度大手1的单循环链表中,既无头结点也无头指针。s为指向某个结点的指
针,试编写算法删除结点*s的直接前驱结点。
#include <iostream>
using namespace std;
int n;
typedef struct DuLNode
{
int data;
struct DuLNode* prior;
struct DuLNode* next;
}DuLNode, * DuLinkList;
void welcome()
{
cout << "1.初始化\n";
cout << "2.输入一个循环链表\n";
cout << "3.输出\n";
cout << "4.删除\n";
cout << "0.退出\n";
cout << endl;
}
void InitList(DuLinkList& L)
{
L = new DuLNode;
L->prior = NULL;
L->next = NULL;
}
void CreatDuList(DuLinkList& L, int n)
{
DuLNode* r;
r = L;
for (int i = 0; i < n; i++)
{
DuLinkList p;
p = new DuLNode;
cin >> p->data;
p->next = L;
p->prior = r;
r->next = p;
L->prior = p;
r = p;
}
}
void display(DuLinkList& L)
{
DuLNode* p;
p = L->next;
for (int i = 0; i < n; i++)
{
cout << p->data << " ";
p = p->next;
}
}
void Delete(DuLinkList& L, int e)
{
DuLinkList p;
p = L->next;
for (int i = 0; i < n; i++)
{
if (e == p->data)
{
p->prior->prior->next = p;
p->prior = p->prior->prior;
cout << "删除成功!";
n--;
return;
}
p = p->next;
}
cout << "删除失败!没有找到该元素!" << endl;
}
int main()
{
DuLinkList L;
L = new DuLNode;
L->prior = NULL;
L->next = NULL;
welcome();
int o;
bool a = true;
while (a)
{
cout << endl << "请选择:";
cin >> o;
switch (o)
{
case 1:
{
InitList(L);
cout << "成功构建一个空的循环链表!";
break;
}
case 2:
{
cout << "请输入链表长度!";
cin >> n;
cout << "请输入链表元素!";
CreatDuList(L, n);
cout << "循环链表创建成功!";
break;
}
case 3:
{
cout << "链表元素为:";
display(L);
break;
}
case 4:
{
cout << "请输入您要删除结点的后驱元素:";
int e;
cin >> e;
Delete(L, e);
break;
}
case 0:
{
a = false;
}
}
}
return 0;
}