//IntList and Linked Data Structures
//IntList
/* Defines a recursive list of integers.*/
public class IntList{
public int head;
public IntList tail;
public IntList(int h, IntList t){
head = h;
tail = t;
}
/* Returns the size of the recursive IntList */
public int size(){
if(this.tail == null)
return 1;
int personInFrontOfMeSize = this.tail.size();
return personInFrontOfMeSize + 1;
}
/* Iterative methods are often uglier. */
public int iterativeSize(){
IntList p = this;
int size = 0;
while(p != null){
size = size + 1;
p = p.tail;
}
return size;
}
/index /
public int get(int i){
if(i == 0){
return this.head;
}
return this.tail.get(i - 1);
}
public static void main(String[] args){
IntList L = new IntList(10, null);
L.tail = new IntList(15, null);
System.out.println(L.head);
System.out.println(L.tail.head);
System.out.println(L.size());
System.out.println(L.iterativeSize());
}
}
//IntListOps
public class IntListOps{
/* returns identical to L, but with every item
*incremented by x, L cannot change.
*/
public static IntList incrList(IntList L, int x){
if(L == null)
return null;
int newHead = L.head + x;
IntList newTail = incrList(L.tail, x);
return new IntList(newHead, newTail);
}
public static void main(String[] args){
//测试代码
}
此段代码为CS61b课程第三节课的演示代码,由于没有直接现成的可复制粘贴,便手打于此,以便今后翻阅。主要部分便是递归与迭代方面的运用,也是着重记录这部分。对于CS61b的课程,先是介绍java的基础知识,之后便是数据结构的介绍。目前只看了前三节课,之后的课程还需继续坚持,同时,作业和lab也要尽量写。
这个暑假已经被自己荒废了不少,继续努力吧!