标签:
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; }
标签:
原文地址:http://www.cnblogs.com/jx-yangbo/p/4857535.html