Java——两个顺序链表的并交集

求两个顺序链表的交集,假设链表是递增的。

public static LinkedList listIntersection(LinkedList L1, LinkedList L2){
        LinkedList intersection = new LinkedList<>();
        Iterator iter1 = L1.iterator();
        Iterator iter2 = L2.iterator();
        int a = iter1.next();
        int b = iter2.next();
        while(true){
            if(a == b){
                intersection.add(a);
                if(iter1.hasNext() && iter2.hasNext()){
                    a = iter1.next();
                    b = iter2.next();
                }
                else    break;
            }
            else if (a > b) {
                if(iter2.hasNext())
                    b = iter2.next();
                else    break;
            }
            else {
                if(iter1.hasNext())
                    a = iter1.next();
                else    break;
            }
        }
        return intersection;
    }

求两个顺序链表的并集,假设链表是递增的。

public static LinkedList listUnion(LinkedList L1, LinkedList L2){
        LinkedList union = new LinkedList<>();
        Iterator iter1 = L1.iterator();
        Iterator iter2 = L2.iterator();
        int a = iter1.next();
        int b = iter2.next();

        while(true){
            if(a == b){
                union.add(a);
                if(iter1.hasNext() && iter2.hasNext()){
                    a = iter1.next();
                    b = iter2.next();
                }else   break;
            }
            else if (a > b) {
                union.add(b);
                if(iter2.hasNext())
                    b = iter2.next();
                else    break;
            }
            else {
                union.add(a);
                if(iter1.hasNext())
                    a = iter1.next();
                else    break;
            }
        }
        while(iter1.hasNext())  union.add(iter1.next());
        while(iter2.hasNext())  union.add(iter2.next());
        return union;
    }

你可能感兴趣的:(Java历-例-程)