java 未赋值变量_Java 小白求教,这里变量没有被赋值为什么会变?

重新实现了简单的 LinkedList,关键逻辑如下:

public void reverse()中调用了 first.reverse(),而 reverse 中并没有对变量 last 做任何操作啊,只是对 first 做了修改,最后调试发现最后一次执行完 this.next = newNext;这一行(53 行)的时候,last 的值就会改变。我看来 last 作为一个独立的变量怎么不应该被 this 影响到啊,想了一下午也没搞明白,求教,感谢送上。

下面是完整代码,问题只和两个 reverse 方法有关。

public interface List {

void add(T value);

T get(int index);

int size();

T remove(int index);

void reverse();

}

public class LinkedList implements List {

private LLNode first, last;

class LLNode {

T value;

LLNode next;

LLNode(T value, LLNode next) {

this.value = value;

this.next = next;

}

T getLL(int index) {

if (index == 0) {

return value;

} else {

if (next == null) {

throw new IndexOutOfBoundsException("error");

}

return next.getLL(index - 1);

}

}

T removeLL(int index) {

if (next == null) {

throw new IndexOutOfBoundsException("error");

}

if (index == 1) {

T value = next.value;

next = next.next;

return value;

} else if (index > 1) {

return next.removeLL(index - 1);

} else {

throw new IndexOutOfBoundsException("error");

}

}

void reverse(LLNode newNext) {

if (next != null) {

next.reverse(this);

}

this.next = newNext;

}

}

@Override

public void add(T value) {

LLNode newNode = new LLNode(value, null);

if (first == null) {

first = last = newNode;

} else {

last.next = newNode;

last = newNode;

}

}

@Override

public T get(int index) {

if (first == null) {

throw new IndexOutOfBoundsException("error");

}

return first.getLL(index);

}

@Override

public T remove(int index) {

if (first == null) {

throw new IndexOutOfBoundsException("error");

}

if (index == 0) {

T value = first.value;

first = first.next;

return value;

}

return first.removeLL(index);

}

@Override

public void reverse() {

if (first == null) {

return;

}

first.reverse(null);

LLNode tmp = last; //不明白这里 first.reverse 没有给 last 赋值,按理说这里

//last 的 next=null,但是为什么会是一个 next 等于 value=17 的 LLNode 类型数据呢

last = first;

first = tmp;

}

public static void main(String[] args) {

List list = new LinkedList<>();

list.add(17);

list.add(34);

list.reverse();

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值