【发布时间】:2022-01-18 09:38:14
【问题描述】:
我不知道这是一个愚蠢的问题,还是它的起源,但我的问题是我正在创建一个包含添加方法的链接列表类
public void addFirst(int data){
node node = new node(data);
if (head == null) {
head = node;
tail = node;
currentSize++;
}
else
node.next = head;
head = node;
currentSize++;
}
} 所以当我这样使用它时:
public static void main(String argas[]){
Linkedlist list = new Linkedlist();
list.addFirst(5)
list.addFirst(10)
list.addFirst(15)
list.addFirst(20)
包含 5 的节点与包含 10 的节点和其余节点具有相同的名称, 它是如何工作的?
完整代码
public class LinkedList {
class node {
int data;
node next;
public node(int data) {
this.data = data;
next = null;
}
public node(){
}
}
private node head;
private node tail;
private int currentSize;
public LinkedList (){
head = null;
currentSize = 0;
}
public void addFirst(int data){
node node = new node(data);
if (head == null) {
head = node;
tail = node;
currentSize++;
}
else
node.next = head;
head = node;
currentSize++;
}
public void addLast(int data){
node node = new node(data);
node tmp = new node();
if (head == null) {
head = node;
tail = node;
currentSize++;
return;
}
tail.next = node;
tail = node;
currentSize++;
return;
}
public void removeFirst(){
if (head == null){
return;
}
if (head == tail){
head = tail = null;
currentSize--;
}
else
head = head.next;
currentSize--;
}
public void removeLast(){
if (head == null){
return;
}
if (head == tail){
head = tail = null;
return;
}
else {
node tmp = new node();
tmp = head;
while (tmp.next != tail){
tmp = tmp.next;
}
tmp.next = null;
tail = tmp;
currentSize--;
}
}
public void printList(){
node tmp = new node();
tmp = head;
while (tmp != null){
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public void size(){
System.out.println((currentSize));
}
}
【问题讨论】:
-
这里的name是什么意思?顺便说一句,你应该处理你的类命名:
node node应该是Node node,即类名应该以大写字母开头以避免与变量名混淆。 -
另一个注意事项:您还应该处理代码格式,并且即使是单语句块也最好使用花括号。现在,您的 else 块可能很难发现错误或意图,即
head = node;是否打算在 else 块内? (现在不是) -
@Thomas 我的意思是:当我们创建一个新节点时,这就是发生的事情 Node node = new Node(data);每次我们创建一个新节点时,我们都会使用名称“node”创建它,这怎么可能
-
你必须了解Java中的
variable scopes和references。这会让你更清楚 -
@GhostCat 谢谢
标签: java linked-list nodes