Skip to content

Commit b24402d

Browse files
committed
added lecture 2 live code
1 parent cc614ae commit b24402d

File tree

2 files changed

+81
-0
lines changed

2 files changed

+81
-0
lines changed

lec3/live2/IntList.java

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
/** Defines a recursive integer list.
2+
* @author Josh Hug
3+
*/
4+
5+
public class IntList {
6+
public int head;
7+
public IntList tail;
8+
9+
public IntList(int h, IntList t) {
10+
head = h;
11+
tail = t;
12+
}
13+
14+
/** Returns the number of items in this IntList */
15+
public int size() {
16+
// if (tail.null == 0) { that was weird
17+
if (tail == null) {
18+
return 1;
19+
}
20+
return 1 + tail.size();
21+
}
22+
23+
/** Returns the size, not using recursion. */
24+
public int iterativeSize() {
25+
IntList p = this;
26+
int size = 0;
27+
while (p != null) {
28+
size = size + 1;
29+
p = p.tail;
30+
}
31+
return size;
32+
}
33+
34+
/** Return ith item of int list */
35+
public int get(int i) {
36+
if (i == 0) {
37+
return head;
38+
}
39+
return tail.get(i - 1);
40+
}
41+
42+
public String toString() {
43+
if (tail == null)
44+
return Integer.toString(head);
45+
return Integer.toString(head) + " " + tail.toString();
46+
}
47+
48+
public static void main(String[] args) {
49+
IntList L = new IntList(10, null);
50+
L.tail = new IntList(614, null);
51+
/*System.out.println(L.head);
52+
System.out.println(L.tail.head);
53+
System.out.println(L.size());*/
54+
System.out.println(L.iterativeSize());
55+
System.out.println(L.get(50));
56+
}
57+
}

lec3/live2/IntListOps.java

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* @author Josh Hug
3+
*/
4+
5+
public class IntListOps {
6+
/** Returns list identical to L, but with
7+
* each item incremented by x. Not changing
8+
* L in any way */
9+
public static IntList incrList(IntList L, int x) {
10+
if (L == null)
11+
return null;
12+
13+
int desiredHead = L.head + x;
14+
IntList desiredTail = incrList(L.tail, x); ///the rest of the list incremented by x
15+
return new IntList(desiredHead, desiredTail);
16+
}
17+
18+
public static void main(String[] args) {
19+
IntList L = new IntList(10, null);
20+
L.tail = new IntList(614, null);
21+
IntListOps slops = new IntListOps();
22+
System.out.println(IntListOps.incrList(L, 5));
23+
}
24+
}

0 commit comments

Comments
 (0)