雙鏈表與單鏈表對比,多了一個指向前驅的指針,其他類同
#include<iostream>
using namespace std;
typedef struct LNode
{
int data;
struct LNode *next,*prior;
}LNode,*Link;
void Init_Link(Link &L)
{
L = new LNode;
L->next = NULL;
L->prior = NULL;
}
void Insert_Link(Link &L,int i,int e)
{
if(i < 1)
return;
Link p;
p = L;
int j = 1;
while(p && j < i)
{
p = p->next;
j++;
}
LNode *s;
s = new LNode;
s->data = e;
if(p->next != NULL)
p->next->prior = s;
s->next = p->next;
s->prior = p;
p->next = s;
}
void Traverse(Link L)
{
Link p;
p = L->next;
while(p)
{
cout << p->data << " ";
p = p->next;
}
}
int searchElemPrior(Link L,int i)
{
if(i == 1)
return 0;
Link p;
p = L->next;
int j = 1;
while(p && j < i)
{
p = p->next;
j++;
}
return p->prior->data;
}
int main()
{
Link L;
Init_Link(L);
for(int i = 1; i < 5; i++)
{
Insert_Link(L,i,i);
}
Insert_Link(L,3,5);
Traverse(L);
cout <<endl;
int a = searchElemPrior(L,5);
cout << a ;
return 0;
}