1. 程式人生 > >單鏈表求兩個集合交集

單鏈表求兩個集合交集

#include

using namespace std;

template struct node { t data; node*next; }; template class linklist { public: linklist(); //建立只有頭結點的空連結串列 linklist(t a[],int n);//建立有n個元素的空連結串列 ~linklist(); int length(); t get(int i); int locate(t x); void insert(int i,t x); t Delete(int i); void printlist(); private: node*first; //單鏈表的頭指標; }; template void linklist::printlist() { node *p; p=first->next; while(p!=NULL) { cout<data<<" “; p=p->next; } cout<<endl; }; template int linklist::length() { node*p; int count; p=first->next;count=0; while(p!=NULL) { p=p->next; count++; } return count; }; template int linklist::locate(t x) { int count; node*p; p=first->next;count=1; while(p!=NULL) { if(p->datax)return count; p=p->next; count++; } return 0; }; template void linklist::insert(int i,t x) { int count; node *p; node *s; p=first;count=0; while(p!=NULL&&count<i-1) { p=p->next; count++; } if(p

NULL)throw"位置”; else{ s=new node;s->data=x; s->next=p->next;p->next=s; } }; template linklist::linklist() { first=new node; first->next=NULL; }; template //頭插法 linklist::linklist(t a[],int n) { node *s; first=new node;first->next=NULL; for(int i=0;i<n;i++) { s=new node;s->data=a[i]; s->next=first->next;first->next=s; } };

template t linklist::Delete(int i) { t x; int count; node *p=first,*q;count=0; while(p!=NULL&&count<(i-1)) { p=p->next; count++; } if(pNULL||p->nextNULL)throw"位置"; else{ q=p->next;x=q->data; p->next=q->next; delete q; return x; } }; template linklist::~linklist() { node *q; while(first!=NULL) { q=first; first=first->next; delete q; } } template t linklist::get(int i) { node *p=first->next; int j=1; while (p && j<i) { p=p->next; j++; } if (!p) throw “位置”; else return p->data; } template void ajb(linklist &A,linklist &B) { t x; linklist c; for(int i=1;i<=B.length();i++) { x=B.get(i);//cout<<x<<" "<<A.locate(x)<<endl; if(A.locate(x)!=0) { // B.Delete(i); c.insert(1,x); } } c.printlist(); }; int main() { int a[5]={1,3,4,5,7}; linklist A(a,5); A.printlist(); cout<<A.get(3)<<endl; cout<<A.length()<<endl; cout<<A.locate(3)<<endl; A.insert(2,10); A.printlist(); int b[4]={3,4,6,7}; linklist B(b,4); B.printlist(); cout<<B.get(3)<<endl; cout<<B.length()<<endl; cout<<B.locate(3)<<endl; B.insert(2,10); B.printlist(); ajb(A,B); return 0; }