分别以两个(带头结点的)循环有序链表表示集合A和B,完成这两个集合并集的操作:
代码如下:
#include<stdio.h> typedef struct LNode { int data ; struct LNode *next ; }LNode , *LinkList ; void union_OL(LinkList &La , LinkList &Lb ) { LinkList pa = La->next->next ; LinkList pb = Lb->next->next ; LinkList rc = La->next ; while(pa != La->next && pb !=Lb->next) { if((pa->data) < (pb->data)) { rc->next = pa ; rc = pa ; pa = pa->next ; } else if((pa->data) > (pb->data)) { rc->next = pb ; rc = pb ; pb = pb->next ; } else { rc->next = pa ; rc = pa ; pa = pa->next ; pb = pb->next ; } } if(pb==(Lb->next)) rc->next = pa ; else{ Lb->next = La->next ; La->next = pb ; La = Lb ; } //printf("%d ",La->next->next->data) ; LinkList hrc = La->next->next ; while(hrc != La->next) { printf("%d ",hrc->data) ; hrc =hrc->next ; } printf(" ") ; } int main() { LinkList La , Lb ; int a[] = {4,7,10,21,40,56} ; int b[] = {7,9,21,68} ; int i ; LinkList ha = new LNode ; La = ha ; for(i = 0 ; i < 6 ; i++) { LinkList s = new LNode ; s->data = a[i] ; La->next = s ; La = s ; } La->next = ha ; LinkList hb = new LNode ; Lb = hb ; for(i = 0 ; i < 4 ; i++) { LinkList s = new LNode ; s->data = b[i] ; Lb->next = s ; Lb = s ; } Lb->next = hb ; /*LinkList hrc = Lb->next->next ; printf("%d ",hrc->data) ; while(hrc != Lb->next) { printf("%d ",hrc->data) ; hrc = hrc->next ; }*/ //inkList rc = La->next ; union_OL(La,Lb) ; return 0 ; }