双向链表C++

#include "stdafx.h"
#include <iostream>
#include <stdio.h>
using namespace std;

#define ERROR  0
#define OVERFLOW  -1
#define OK 0x1

typedef int Status;
typedef int ElemType;

typedef struct DNode{
struct DNode *front;
ElemType data;
struct DNode *next;
}DNode,*LinkList;

LinkList GetDNode(LinkList &L,int i);
Status InitList(LinkList &L);
Status ListInsert(LinkList &L,int i, ElemType e);
LinkList GetDNode(LinkList &L,int i);
int ListLength(LinkList &L);

// Init Double list
Status InitList(LinkList &L)
{
L =(LinkList)malloc(sizeof(DNode));
if(!L)  return OVERFLOW;
L->next = NULL;
return OK;
}

// Insert double list
Status ListInsert(LinkList &L,int i, ElemType e)
{
LinkList P,S;
if(i<1 || i>ListLength(L)+1)  return ERROR;
P = GetDNode(L,i-1);
S = (LinkList)malloc(sizeof(DNode));
if(!S)  return OVERFLOW;

S->next  = P->next;
P->next = S;
S->data = e;
S->front = P;
if(S->next)
S->next->front = S;
return OK;
}


// Get the pre-Node of the current node
LinkList GetDNode(LinkList &L,int i)
{
LinkList P;
P = L;
for(int j=1;j<=i;++j)
{
P = P->next;
}
return P;
}

// Delete one of the double node
Status ListDelete(LinkList &L,int i)
{
LinkList P,P1;
if(i<1 || i>ListLength(L))
return ERROR;
P = GetDNode(L,i-1);
P1 = P->next;
if(P->next->next)  // delete the non-last node
{
P->next = P1->next; //netx
P1->next->front = P;
free(P1);
}
else
{
P->next = NULL;
P1->front = NULL;
free(P1);
}

return OK;
}

// calculate the length of double list
int ListLength(LinkList &L)
{
int i = 0;
LinkList P;
P = L->next;
while(P)
{
P = P->next;
++i;
}
return i;
}


void Travese(LinkList &L, void (*visit)(ElemType e))
{
LinkList P;
P = L->next;
while(P)
{
visit(P->data);
P = P->next;
}
}


void print(ElemType e)
{
printf("%d\n",e);
}


int _tmain(int argc, _TCHAR* argv[])
{
LinkList head;
InitList(head);
for(int i=1;i<=5;++i)
ListInsert(head,i,2*i);
Travese(head,print);
ListInsert(head, 4,20);
Travese(head,print);

ListDelete(head, 5);
Travese(head,print);
return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值