中级农民
- 积分
- 251
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2015-4-23
- 最后登录
- 1970-1-1
|
本帖最后由 Casualet 于 2015-6-16 19:43 编辑
public class d2{
public static IntList SquareDestructive(IntList l){
if(l.tail==null){
l.head=l.head*l.head;
return null;
}
l.head=l.head*l.head;
SquareDestructive(l.tail);
return l;
}//recursive
public static IntList SquareDestructiveV2(IntList l){
IntList L=l;
while(l.tail!=null){
l.head=l.head*l.head;
l=l.tail;
}
l.head=l.head*l.head;
return L;
}//iterative
public static IntList SquareNonDestructive(IntList l){
if(l.tail==null)
return new IntList(l.head*l.head,null);
return new IntList(l.head*l.head,SquareNonDestructive(l.tail));
}//recursive
public static IntList SquareNonDestructiveV2(IntList l){
IntList L,next,temp;
L=new IntList(l.head*l.head,null);
next=L;
while(l.tail!=null){
l=l.tail;
temp= new IntList(l.head*l.head,null);
next.tail=temp;
next=next.tail;
}
// next.tail=new IntList(l.head*l.head,null);
return L;
}//iterative
public static IntList reverseNonDestructive(IntList lst){
IntList cur,next,myCur,myNext=null;
cur=lst;
next=cur.tail;
myCur=new IntList(cur.head,null);
if(next==null) return myCur;
while(next!=null){
myNext=new IntList(next.head,null);
myNext.tail=myCur;
myCur=myNext;
cur=cur.tail;
next=next.tail;
}
return myNext;
}
public static IntList reverseDestructive(IntList lst){
IntList cur,next,nextTemp;
cur=lst;
next=cur.tail;
cur.tail=null;
if(next==null) return cur;
while(next!=null){
if(next.tail!=null){
nextTemp=next.tail;
next.tail=cur;
cur=next;
next=nextTemp;
}else{
break;
}
}
next.tail=cur;
return next;
}
public static void printList(IntList l){
while(l.tail!=null){
System.out.print(l.head+" ");
l=l.tail;
}
System.out.println(l.head);
}
public static void main(String args[]){
IntList l=new IntList(4,null);
l=new IntList(3,l);
l=new IntList(2,l);
l=new IntList(1,l);
printList(l);
SquareDestructive(l);
printList(l);
SquareDestructiveV2(l);
printList(l);
IntList L=SquareNonDestructive(l);
printList(L);
L=SquareNonDestructive(L);
printList(L);
L= reverseNonDestructive(L);
printList(L);
L= reverseDestructive(L);
printList(L);
}
}
第一题不知道为什么倒了;图片是测试结果,0是因为overflow; V2表示的是bonus版本;
|
|