您的位置:首页 > 其它

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

2015-11-11 18:01 381 查看
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=0;
int start = 0;
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: