#include<iostream>
using namespace std;
struct Node
{
int data;
Node *next;
Node* prior;
};
typedef Node* LinkList;
void init(LinkList* List);
bool insert(LinkList *List, int location, int data);
void show_position(LinkList L);
void show_reverse(LinkList L);
bool Delete(LinkList *List, int location);
int main()
{
LinkList List;
init(&List);
for (int i = 1; i <= 10; i++)
{
insert(&List, i, i*10);
}
Delete(&List, 1);
show_position(List);
show_reverse(List);
system("pause");
return 0;
}
void init(LinkList* List)
{
LinkList s = (LinkList)malloc(sizeof(Node));
s->data = -1;
s->next = s;
s->prior = s;
*List = s;
}
bool insert(LinkList *List, int location, int data)
{
int j = 1;
LinkList p = *List;
if (location < 1)
{
cout << "insert erro" << endl;
return false;
}
//与非循环链表不同,这边循环的条件为next不为空。原因是初始情况,指针就是为*List,如果用旧方法,无法进行循环。
while (j < location&&p->next!= *List)
{
j++;
p = p->next;
}
if (j != location)
{
cout << "insert erro" << endl;
return false;
}
LinkList s = (LinkList)malloc(sizeof(Node));
s->data = data;
s->next = p->next;
s->prior = p;
p->next = s;
s->next->prior = s;
}
void show_position(LinkList L)
{
LinkList p = L->next;
cout << "position direction: ";
while (p != L)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void show_reverse(LinkList L)
{
LinkList p = L->prior;
cout << "reverse direction: ";
while (p != L)
{
cout << p->data << " ";
p = p->prior;
}
cout << endl;
}
bool Delete(LinkList *List, int location)
{
int j = 1;
LinkList p = *List;
if (location < 1)
{
cout << "delete erro" << endl;
return false;
}
while (j < location&&p->next != *List)
{
j++;
p = p->next;
}
if (p->next == *List)
{
cout << "delete erro" << endl;
return false;
}
p = p->next;//指向要删除的节点
p->prior->next = p->next;
p->next->prior = p->prior;
return true;
}
【数据结构】循环双向链表
最新推荐文章于 2024-08-03 09:58:03 发布