首页 > 代码库 > 循环双链表

循环双链表

#include<iostream>using namespace std;struct LinkNode{   int value;   LinkNode* next;   LinkNode* pre;};LinkNode* createDoubleRoundLinkList(){    LinkNode* head = (LinkNode*)malloc(sizeof(LinkNode));    head->next=head;    head->pre=head;    head->value=http://www.mamicode.com/0;    return head;}bool insertElem(int pos,int value,LinkNode* head){    if(pos<=0)return 0;    LinkNode* p = head;    int j=0;    while(p->next!=head && j<pos-1)//任然定位到pos-1的元素,也就是待插入元素的位置前一个,其实书上写的是到POS位置,但这样不能插在末尾了    {                                         p=p->next;         j++;    }    if(j==pos-1)    {        LinkNode* newNode = (LinkNode*)malloc(sizeof(LinkNode));        newNode->value=http://www.mamicode.com/value;        newNode->next=p->next;        p->next=newNode;        newNode->pre=p;        if(newNode->next)//针对在链表末端的一个边界            newNode->next->pre=newNode;        head->value++;        return 1;    }    return 0;}bool deleElem(int pos,LinkNode* head){    if(pos<=0)return 0;    LinkNode* p = head;    int j=0;    while(p->next!=head && j<pos)    {        p=p->next;        j++;    }    if(j==pos)//这里可以定位到pos的元素,也就是待删除元素的位置,这里通过j==pos判断出合法情况,之所以不用p==head原因和循环单链表的一样    {        p->pre->next=p->next;        p->next->pre=p->pre;//p->next不会为空        delete(p);        head->value--;        return 1;    }    return 0;}void clearLinkList(LinkNode* head){    LinkNode*p = head->next;    while(p!=head)     {        LinkNode* q = p->next;        deleElem(1,head);//每次删除第一个,逐个删除        p=q;    }}void destroyLinkList(LinkNode* head){   clearLinkList(head);   delete head;   head = 0;}void outPut(LinkNode* head){    if(head == NULL)    {       cout<<"link list dose not exist"<<endl;       return;    }    if(head->value=http://www.mamicode.com/=0)    {        cout<<"link list is empty"<<endl;        return;    }    LinkNode* p = head->next;    while(p!=head)    {         cout<<p->value<<" ";         p=p->next;    }    cout<<endl;}void main(){    int len=12;    LinkNode* L= createDoubleRoundLinkList();    int v;    for(int i=0;i<len;i++)    {         v = rand() % 100;         cout<<v<<" ";         insertElem(1,v,L);//每次在链表尾部插入,使得输入的顺序和链表中的顺序相反    }    cout<<endl;    outPut(L);    destroyLinkList(L);   //outPut(L);    L= createDoubleRoundLinkList();    for(int i=0;i<len;i++)    {         v = rand() % 100;         cout<<v<<" ";         insertElem(L->value+1,v,L);//每次在链表尾部插入,使得输入的顺序和链表中的顺序一致    }    cout<<endl;    outPut(L);    insertElem(3,999,L);    outPut(L);    insertElem(100,999,L);    outPut(L);    insertElem(L->value,9999,L);    outPut(L);    insertElem(L->value+1,8888,L);    outPut(L);    insertElem(1,7777,L);    outPut(L);    deleElem(1,L);    outPut(L);    deleElem(100,L);    outPut(L);    deleElem(7,L);    outPut(L);    deleElem(L->value,L);    outPut(L);    deleElem(L->value+1,L);    outPut(L);    clearLinkList(L);    outPut(L);    insertElem(1,2,L);    outPut(L);    deleElem(L->value,L);    outPut(L);    cin>>len;}

 

循环双链表