//带头节点 #include <iostream> using namespace std; typedef int ElemType; typedef struct Node { ElemType data; struct Node *next; }LNode,*LinkList; void InitList(LinkList &L); void CreateCyList(LinkList l); void Output(LinkList l); int ListLength(LinkList l); bool PreElem(LinkList l,ElemType e,ElemType &pre); LinkList MergeCyList(LinkList La,LinkList lb); int main(int argc, char const *argv[]) { /* LinkList l; InitList(l); CreateCyList(l); Output(l); cout<<"len:"<<ListLength(l)<<endl; int x; if(PreElem(l,20,x)==true) cout<<"20的前驱元素为"<<x<<endl; */ LinkList l1,l2; InitList(l1); InitList(l2); CreateCyList(l1); CreateCyList(l2); LinkList p = MergeCyList(l1,l2); Output(p); return 0; } void InitList(LinkList &L) { L = new LNode; L->next = L; } void CreateCyList(LinkList l) { cout<<"请依次输入数据,并以-1作为结束标记:\n"; int m; LNode *p = l; while(1) { cin>>m; if(m==-1) break; LNode *s = new LNode; s->data = m; p->next = s; p = s; } p->next = l; } void Output(LinkList l) { LNode *p; p = l->next; while(p!=l) { cout<<p->data<<" "; p = p->next; } cout<<"\n"; } int ListLength(LinkList l) { LNode *p; p = l->next; int len = 0; while(p!=l) { len++; p = p->next; } return len; } bool PreElem(LinkList l,ElemType e,ElemType &pre) { LNode *p,*q; p = l->next; q = p->next; while(q!=l->next) { if(q->data==e) { pre = p->data; return true; } p = q; q = q->next; } return false; } LinkList MergeCyList(LinkList La,LinkList Lb) { LNode *p,*q; p=La,q=Lb; while(p->next!=La) p = p->next; while(q->next!=Lb) q = q->next; q->next = La; p->next = Lb->next; delete Lb; return La; }
原文地址:http://blog.csdn.net/huolang_vip/article/details/45199589