天天看点

链表,队列,堆栈中的练习

1,给定一个表L和另一个表P他们包含以升序排列的整数,操作在printLots(L,P)将打印L中那些有P所指位置上的元素。写出printLots(L,P)。

public static <AnyType> void printLots(List<AnyType> L,List <Integer> P){
    Iterator<AnyType> iterL = L.iterator();
    Iterator<Integer> iterP = P.iterator();
    AnyType itemL=null;
    Integer itemP=;
    int start = ;
    while ( iterL.hasNext() && iterP.hasNext() )
    {
        itemP = iterP.next();
        System.out.println("Looking for position " + itemP);
        while ( start < itemP && iterL.hasNext() )
        {
            start++;
            itemL = iterL.next();
        }
    System.out.println( itemL );
    }
}
           

2,通过只调整链表来交换两个相邻的元素,使用

a.单链表

b.双链表

(a) For singly linked lists:

public static void swapWithNext( Node beforep )
{
Node p, afterp;
p = beforep.next;
afterp = p.next; // Both p and afterp assumed not null.
p.next = afterp.next;
beforep.next = afterp;
afterp.next = p;
}
           

(b) For doubly linked lists:

public static void swapWithNext( Node p )
{
Node beforep, afterp;
beforep = p.prev;
afterp = p.next;
p.next = afterp.next;
beforep.next = afterp;
afterp.next = p;
p.next.prev = p;
p.prev = afterp;
afterp.prev = beforep;
}
           

继续阅读