# 数据结构基础：双链表结构、实现

## 双链表的实现

typedef int LTDataType;
typedef struct ListNode
{
struct ListNode* next; //指针保存下⼀个节点的地址
struct ListNode* prev; //指针保存前⼀个节点的地址
LTDataType data;
}LTNode;

### 头插

DLinkList HeadInsert(DLinkList &L)
{
InitList(L);
int x;
cin>>x;
while(x!=9999)
{
LTNode *s = (LTNode *)malloc(sizeof(LTNode));
s->data = x;
if(L->next == NULL)
{
s->next = NULL;
s->pre = L;
L->next = s;
}
else
{
s->next = L->next;
L->next->pre = s;
s->pe = L;
L->next = s;
}
cin>>x;
}
return L;
}

### 尾插

DLinkList TailInsert(DLinkList &L)
{
InitList(L);
LTNode *s,*r=L;
int x;
cin>>x;
while(x!=9999)
{
s = (LTNode *)malloc(sizeof(LTNode));
s->data = x;
s->next = NULL;
s->pre = r;
r->next = s;
r = s;
cin>>x;
}
return L;
}

### 遍历双链表

void PrintList(DLinkList L)
{
DNode *p = L->next;
while(p){
cout<<p->data<<" ";
p = p->next;
}
cout<<endl;
}

### 查找

void Delete(DLinkList &L, int i)
{
if(i<1 || i>Length(L))
{
cout<<"delete failed: index is wrong."<<endl;
return;
}
LDNode *p = GetElem(L,i-1);
LDNode *q = p->next;
p->next = q->next;
q->next->pre = p;
free(q);
}


|
10天前
|

13 0
|
1天前

6 1
|
2天前
|

|
5天前
|

7 0
|
5天前

7 0
|
5天前
|

7 0
|
10天前
|

12 0
|
10天前
|

10 2
|
10天前
|

9 0
|
10天前
|

4 0