14

问题

       已知递增有序的单链表A、B和C分别存储了一个集合。设计算法实现,并使求解结构A仍保持递增。要求算法的时间复杂度为O(|A| + |B| + |C|)。其中|A|为集合A的元素个数。

分析

       找B与C的交集,然后并到A中即可。
       可以分析下时间复杂度。

代码

void mergeList(LinkList A, LinkList B, LinkList C){
    LNode *p = A, *pa = A -> next, *pb = B -> next, *pc = C -> next;
    while(pb && pc) {
        if(pb -> data < pc -> data) {
            pb = pb -> next;
        }else if(pb -> data > pc -> data) {
            pc = pc -> next;
        }else if(pb -> data == pc -> data) {
            LNode *temp = (LinkList)malloc(sizeof(LNode));
            temp -> data = pb -> data;
            temp -> next = NULL;
            if(pa -> next == NULL) {
                pa -> next = temp;
                pa = pa -> next;
            }else {
                while(pa) {
                    if(pa -> data > temp -> data) {
                        temp -> next = pa;
                        p -> next = temp;
                        p = p -> next;
                        break;
                    }else if(pa -> data < temp -> data) {
                        pa = pa -> next;
                        p = p -> next;
                    }else if(pa -> data == temp -> data) {
                        pa = pa -> next;
                        p = p -> next;
                        break;
                    }
                }
                if(pa == NULL) {
                    p -> next = temp;
                    pa = temp;
                }
            }
            pb = pb -> next;
            pc = pc -> next;
        }
    }
}

源代码

http://123.206.59.223:8080/code/code/14.rar

阅读更多

没有更多推荐了,返回首页