4. References, Recursion, and Lists
约 287 字小于 1 分钟
2025-04-29
基本类型变量与引用类型变量
在 Java 里面,变量是放在每一个“盒子”里的。
- 基本类型变量有 int、char、double、float 等。这些变量采用
int x = 1;
,在这里x
就是变量。 - 引用类型变量采用
Dog dog = new Dog();
dog 就像一个遥控器,指向 dog 实例变量。
[[Drawing 2025-04-15 10.52.45.excalidraw]]
IntLists
现在开始正式完成这个整型链表。
public class IntList {
public int first;
public IntList rest;
public IntList(int f, IntList r) {
first = f;
rest = r;
}
// 初始化和添加节点:
public static void main(String[] args) {
IntList L = new IntList(15, null);
L = new IntList(10, L);
L = new IntList(5, L);
}
}
整型列表分两个部分:一个是存有节点内部整型值的 first
,一个是存有后继节点地址的指针 rest
。接下来我们为这个 IntList 添加一下 size()
方法,以获取链表的大小。
/** 通过递归来返回链表大小 */
public int size() {
if (rest == null) {
return 1;
}
return 1 + this.rest.size();
}
/** 通过循环来返回链表大小 */
public int iterativeSize() {
IntList p = this;
int totalSize = 0;
while (p != null) {
totalSize += 1;
p = p.rest;
}
return totalSize;
}