双向循环链表使用实例

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

#include

using namespace std;

typedef struct DLNode{ //定义一个双向循环链表char data;

DLNode *next;

DLNode *back;

}DLNode,*DLnode;

int Creat(DLnode root) //创建一个带头节点的双向链表{

root=(DLNode*)malloc(sizeof(DLNode)); //为头节点申请空间

if(root==NULL)

return 0; //创建不成功返回0

root->next=root->back=NULL; //使next和back指针都指向root return 1; //创建成功返回1

}

int Insert(DLnode &root,char x) //插入元素

{

DLNode *p;

DLnode s;

s=root;

p=(DLNode*)malloc(sizeof(DLNode));

if(p==NULL) //插入不成功,返回0

{

cout<<"插入不成功"<

return 0;

}

p->data=x; //插入成功返回1

p->back=s->back;

p->next=s;

s->back->next=p;

s->back=p;

free(p);

free(s);

return 1;

}

int Delete(DLnode &root) //删除

{

DLNode *p,*q;

DLnode s;

p=(DLNode*)malloc(sizeof(DLNode));

q=(DLNode*)malloc(sizeof(DLNode));

s=root;

if(root==NULL) //头指针为空,则删除不成功

{

cout<<"删除不成功"<

return 0;

}

p=s->next;

while(p!=s) //头指针不为空,删除#号前面的字符{

if(p->data!='#')

p=p->next;

else

{

q=p->back;

q->back->next=q->next;

q->next->back=q->back;

}

}

free(p);

free(q);

cout<<"删除成功"<

return 1;

}

void PutOut(DLnode &root) //打印双向链表元素

{

DLNode *p;

if(root==NULL)

{

cout<<"输出不成功"<

}

p=root->next;

while(p!=root)

{

cout<data;

}

cout<

}

void main() //测试程序

{

DLnode root=NULL;

Creat(root);

char x;

cout<<"Enter a line of characters:"<

for(int i=0;i<17;i++)

{

cin>>x;

Insert(root,x);

}

Delete(root);

cout<<"delete the last character:"<

PutOut(root);

DLnode roote=NULL;

Creat(roote);

cout<<"Enter a line of characters:"<

for(int j=0;j<18;j++)

{

cin>>x;

Insert(roote,x);

}

Delete(roote);

cout<<"delete the last character:"<

PutOut(roote);

}

进地址 房间447 密码851

相关文档
最新文档