线性表题 2.19
#include<iostream> using namespace std; #define ElemType double typedef struct LNode { ElemType data; struct LNode* next,*prior; }LNode,*Link; typedef struct { Link head,tail; int length; }LinkList; bool Init_LinkList(LinkList& L)//初始化双向链表L { L.head=new LNode; if(!L.head) return false; L.head->next=L.head->prior=nullptr; L.tail=L.head; L.length=0; return true; } bool Input_LinkList(LinkList& L)//尾插法输入数据 { cout<<"输入数据 非double停止\n"; ElemType num; Link p; while(cin>>num){ p=new LNode; if(!p) return false; p->data=num; p->next=L.tail->next; p->prior=L.tail; L.tail->next=p; L.tail=p; L.length++; } if(!cin){//改变cin的输入状态,以免影响后续的cin使用 cin.clear(); while(cin.get()!='\n') continue; } cout<<"输入完成\n"; return true; } bool DeleteArrangeElem_LinkList(LinkList& L,ElemType mink,ElemType maxk)//删除大于mink、小于maxk的数据 { if(mink>maxk){ cout<<"给的值不合理\n"; return false; } Link p,q; p=L.head->next; while(p&&p->data<=mink) p=p->next; if(!p)//p==nullptr 说明数据全部小于mink,没有要删除的 return true; q=p;//q从p开始 while(q&&q->data<maxk) q=q->next; if(!q){//q==nullptr 说明 从p开始到最后 的这些数据全部小于maxk,这样会影响到尾指针,需重置尾指针 p->prior->next=nullptr; L.tail=p->prior; } else p->prior->next=q;//正常情况,不需要重置尾指针 Link p1; while(p!=q){//删除p(包括p)到q的前驱指针(不包括q) 指向的数据 p1=p; p=p->next; delete p1; L.length--; } return true; } void Output_LinkList(LinkList L)//输出链表数据 { cout<<"----"<<endl; cout<<"链表长度:"<<L.length<<endl; Link p=L.head->next; while(p){ cout<<p->data<<" "; p=p->next; } cout<<endl; cout<<"----"<<endl; } int main() { LinkList L; Init_LinkList(L); Input_LinkList(L); Output_LinkList(L); ElemType a,b; cin>>a>>b; DeleteArrangeElem_LinkList(L,a,b); Output_LinkList(L); return 0; } 输入数据 非double停止 1.1 2.2 3.3 4.4 5.5 @ 输入完成 ---- 链表长度:5 1.1 2.2 3.3 4.4 5.5 ---- 1 6 ---- 链表长度:0 ---- Process returned 0 (0x0) execution time : 5.803 s Press any key to continue.