#include<iostream> using namespace std; struct LinkNode { int value; LinkNode* next; LinkNode* pre; }; LinkNode* createDoubleLinkList() { LinkNode* head = (LinkNode*)malloc(sizeof(LinkNode)); head->next=NULL; head->pre=NULL; head->value=0; return head; } bool insertElem(int pos,int value,LinkNode* head) { if(pos<=0)return 0; LinkNode* p = head; int j=0; while(p!=NULL && j<pos-1)//任然定位到pos-1的元素,也就是待插入元素的位置前一个,其实书上写的是到POS位置,但这样不能插在末尾了 { p=p->next; j++; } if(p!=NULL) { LinkNode* newNode = (LinkNode*)malloc(sizeof(LinkNode)); newNode->value=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!=NULL && j<pos) { p=p->next; j++; } if(p!=NULL)//这里可以定位到pos的元素,也就是待删除元素的位置 { p->pre->next=p->next; if(p->next) p->next->pre=p->pre; delete(p); head->value--; return 1; } return 0; } void clearLinkList(LinkNode* head) { LinkNode*p = head->next; while(p!=NULL) { 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==0) { cout<<"link list is empty"<<endl; return; } LinkNode* p = head->next; while(p!=NULL) { cout<<p->value<<" "; p=p->next; } cout<<endl; } void main() { int len=12; LinkNode* L= createDoubleLinkList(); 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= createDoubleLinkList(); 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; }