gpt4 book ai didi

Java LinkedStack next = head?

转载 作者:行者123 更新时间:2023-11-29 07:51:39 26 4
gpt4 key购买 nike

所以我有这个链接节点堆栈(简称链接堆栈)的代码,它让我非常困惑!我明天要考试,这让我很困惑!所以看看:

class Node<T> {            
T item; // data in node
Node<T> next = null; // successor node

Node(T item0, Node<T> next0) {
item = item0; next = next0;
}
}

这很容易理解没问题,我们创建一个名为 Node 的类(它是一个数据结构),其中包含一个类型为 T 的项。 (可以是字符串、整数等。)和另一个 Node称为 next 以指示行中的下一个节点。一切都清楚了。别这样了!现在是 Stack 的时间了本身,所以这里是代码:

class Stack<T> {

private Node<T> head = null; // first node (null if empty)

Stack() {}

Stack(int n) {}

boolean isEmpty() {return(head==null);}

boolean push(T t) {
head = new Node<>(t,head);
return true; // always space available
}

T pop() {
if (head==null) return null;
T t = head.item;
head = head.next;
return t;
}
}

这就是我失去理智的地方!好的!首先,当我们启动 Stack 时,我们创建了一个 Node用名字 head 好吧!知道了,它是 null是的!接下来,对我来说黑魔法是当我们使用 push(T t)方法。所以我们说 head = new Node<>(t, head)好吧好吧!慢点那家伙!我们替换现有的 null head 有一个包含数据 t 的新节点,作为 下一个 节点,它携带自己??所以 head = data, head(null,null)..?如果我们添加第二个元素怎么办?又是 head = data, head(data, head(null, null)... ?

请用简单的英语向我解释一下! :(

最佳答案

线

head = new Node<>(t,head); 

按顺序执行
1) new Node<>(t,head)
2) head = ...

因此,当您创建新的 Node 时您传递旧值 head 的对象,而不是对自身的引用。

为了减少混淆,这一行可以重写为

Node<T> oldHead = head;
head = new Node<>(t, oldHead);

所以当栈为空时head = null
当我们添加一项时 head = (item1, null)
当我们添加另一个项目时 head = (item2, (item1, null))

关于Java LinkedStack next = head?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20691344/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com