双向链表
创建双向循环链表(不带头结点):
typedef struct DoubleNode{ int number; struct DoubleNode *next; struct DoubleNode *prior; }DoubleNode ,*DoubleList;
DoubleList CreateList(DoubleList head ){ int SIZE,i=0; DoubleList p,q; head=(DoubleList)malloc(sizeof(DoubleNode)); head=NULL; p=head; cin>>SIZE; while(i<SIZE){ q=(DoubleList)malloc(sizeof(DoubleNode)); cin>>q->number; if(head==NULL){ head=q; p=q; } else{ p->next=q; q->prior=p; p=q; } i++; } p->next=head; head->prior=p; return head; } void ShowList(DoubleList head){ DoubleList p; p=head; do{ cout<<p->number<<" "; p=p->next; }while(p!=head); }
带头结点:
DoubleList CreateList(DoubleList head ){ int SIZE,i=0; DoubleList p,q; head=(DoubleList)malloc(sizeof(DoubleNode)); p=head; cin>>SIZE; while(i<SIZE){ q=(DoubleList)malloc(sizeof(DoubleNode)); cin>>q->number; p->next=q; q->prior=p; p=q; i++; } p->next=head; head->prior=p; //最后的完善部分 带不带头结点都一样 return head; } void ShowList(DoubleList head){ DoubleList p; for(p=head->next;p!=head;p=p->next){ cout<<p->number<<" "; } }
插入(带头节点)
//这个情况是 这些整数从第二个开始,递增有序 将第一个结点删除并插入链表中的适当位置 就是说白了插入链中和链尾是不一样的
DoubleList Adjust(DoubleList head){ DoubleList p,temp,q; temp=(DoubleList)malloc(sizeof(DoubleNode)); temp=head->next; head->next=temp->next; (head->next)->prior=head; p=head->next; if(temp->number<head->prior->number){ for(p;p!=head;p=p->next){ if(p->number>temp->number){ q=p->prior; p=q->next; temp->next=p; q->next=temp; temp->prior=q; p->prior=temp; break; } } } else{ temp->next=head; temp->prior=head->prior; head->prior->next=temp; head->prior=temp; } return head; }