CS61B_examprep06
public class AltList<X, Y> { private X item; private AltList<Y, X> next; AltList(X item, AltList<Y, X> next) { this.item = item; this.next = next; } public static void main(String[] args) { AltList<Integer, String> list = new AltList<Integer, String>(5, new AltList<String, Integer>("cat", new AltList<Integer, String>(10, new AltList<String, Integer>("dog", null)))); list.pairsSwapped(); } }
解答:
1 public class AltList<X, Y> { 2 3 private X item; 4 private AltList<Y, X> next; 5 6 AltList(X item, AltList<Y, X> next) { 7 this.item = item; 8 this.next = next; 9 } 10 public AltList<Y, X> pairsSwapped() { //even and nonzero 11 AltList<Y, X> list = new AltList<Y, X>(next.item, new AltList<X, Y>(this.item, null)); 12 if (next.next != null) { 13 list.next.next = next.next.pairsSwapped(); 14 } 15 return list; 16 } 17 18 public static void main(String[] args) { 19 20 AltList<Integer, String> list = 21 new AltList<Integer, String>(5, 22 new AltList<String, Integer>("cat", 23 new AltList<Integer, String>(10, 24 new AltList<String, Integer>("dog", null)))); 25 list.pairsSwapped(); 26 } 27 }
类似的题型


浙公网安备 33010602011771号