码迷,mamicode.com
首页 > 编程语言 > 详细

C++双向循环链表

时间:2015-10-06 19:31:12      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:

DuLink:

#include<iostream>
using namespace std;
typedef int elemType;

typedef struct DulNode
{
    elemType data;
    DulNode *prior;
    DulNode *next;
}*DuList;

void InitList(DuList *L)
{
    *L = new DulNode;
    (*L)->next = (*L)->prior = *L;
}

int LengthList(DuList *L)//获取表长
{
    DuList p = (*L)->next;
    int length = 0;
    while((p!=NULL) && (p!=*L))
    {
        p = p->next;
        length++;
    }
    return length;
}

//获取第pos个位置的元素,若正确获取返回1,否则返回0
int GetElem(DuList *L, int pos, elemType *x)
{
    DuList p = (*L)->next;
    int i=1;
    while(p!=(*L) && i<pos)
    {
        p=p->next;
        i++;
    }
    if(p==*L || i>pos)
    {
        cout<<"get position error"<<endl;
        return 0;
    }
    *x = p->data;
    return 1;
}

//在带头结点的双向循环链表的第pos个位置前插入元素e
bool InsertList(DuList *L, int pos, elemType e)
{
    DuList p,q;
    int i=1;
    p = (*L)->next;
    while(p!=*L && i<pos-1)
    {
        p = p->next;
        i++;
    }
    if((p==*L|| i>pos-1) && ((*L)->next!=(*L)->prior))
        return false;
    q = new DulNode;
    q->data = e;

    q->prior = p;
    q->next = p->next;
    p->next->prior = q;
    p->next = q;
}

//删除第pos个位置的元素
bool DeleteList(DuList *L, int pos)
{
    DuList p,q;
    int i=1;
    p = (*L)->next;
    while(p!=*L && i<pos)
    {
        p = p->next;
        i++;
    }
    if((p==*L|| i>pos) && ((*L)->next!=(*L)->prior))
        return false;

    p->prior->next = p->next;
    p->next->prior = p->prior;
}

void PrintList(DuList *L)
{
    DuList p;
    int i=1;
    p = (*L)->next;
    while(p!=*L)
    {
        cout<< i <<":\t"<< p->data << endl;
        p = p->next;
        i++;
    }
}

int main()
{
    DuList L;
    InitList(&L);
    int length;
    for(int i=1;i<6;i++)
        InsertList(&L,i,i);
    cout<<"the length of Dulist is: "<< LengthList(&L) <<endl;
    PrintList(&L);
    cout<<endl;

    int num;
    GetElem(&L, 2, &num);
    cout<<"the 2th item of list is: "<< num <<endl;

    DeleteList(&L, 3);
    cout<<"after delete the 3th item:"<<endl;
    PrintList(&L);
    cout<<endl;

    return 0;
}

 

C++双向循环链表

标签:

原文地址:http://www.cnblogs.com/jx-yangbo/p/4857535.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!