双向链表的两种实现
上次我们学习了单链表,这次我们来看双链表,双链表与单链表相比 ,我们知道,单链表只能通过索引(next指针)找到他的后继,而若要找他的前驱就需要从头遍历,非常麻烦,所以我们在单连链表的基础上多加一个指针域,指向它的前驱,这样我们找每个元素都能在o(1)的复杂度内,找到他的前驱。
接下来我们来看具体的代码实现:
1.动态链表
#include<iostream>
using namespace std;
typedef struct Noid {
int data;
struct Noid* left;
struct Noid* right;
}list , *listlink;
void list_creat(listlink head ,int data)
{
listlink p;
p = head;
while (p->right)
{
p = p->right;
}
listlink m = new list;
m->data = data;
//m->left = NULL;
m->right = NULL;
p->right = m;
m->left = p;
}
//在第k个后面插入(这里不算头节点)
void insert(listlink head , int k , int x )
{
listlink p = head->right;
while (--k)
{
p = p->right;
}
listlink s = new list;
s->data = x;
s->right = p->right;
s->left = p;
p->right->left = s;
p->right = s;
}
//删除第k个数
void remove(listlink head, int k)
{
listlink p;
p = head->right;
while (--k)
{
p = p->right;
}
p->left->right = p->right;
p->right->left = p->left;
delete p;
p = NULL;
}
//反转
listlink reverse(listlink head)
{
int i = 0;
listlink p = head;
while (p->right)
{
++i;
p = p->right;
}
cout << i << endl;
return p;
}
int main()
{
listlink head = new list;
head->left = NULL;
head->right = NULL;
head->data = 0;
int a[5] = {1,2,3,4,5};
int n = 5;
while (n--)
list_creat(head, a[n]);
insert(head, 2, 6);
remove(head, 2);
listlink hix;
hix = reverse(head);
while (hix->left)
{
cout << hix->data << ' ';
hix = hix->left;
}
return 0;
}
2.静态链表
#include <iostream>
using namespace std;
const int N = 100010;
int m;
int e[N], l[N], r[N], idx;
// 在节点a的右边插入一个数x
void insert(int a, int x)
{
e[idx] = x;
l[idx] = a, r[idx] = r[a];
l[r[a]] = idx, r[a] = idx ++ ;
}
// 删除节点a
void remove(int a)
{
l[r[a]] = l[a];
r[l[a]] = r[a];
}
int main()
{
cin >> m;
// 0是左端点,1是右端点
r[0] = 1, l[1] = 0;
idx = 2;
while (m -- )
{
string op;
cin >> op;
int k, x;
if (op == "L")
{
cin >> x;
insert(0, x);
}
else if (op == "R")
{
cin >> x;
insert(l[1], x);
}
else if (op == "D")
{
cin >> k;
remove(k + 1);
}
else if (op == "IL")
{
cin >> k >> x;
insert(l[k + 1], x);
}
else
{
cin >> k >> x;
insert(k + 1, x);
}
}
for (int i = r[0]; i != 1; i = r[i]) cout << e[i] << ' ';
cout << endl;
return 0;
}