多个对象如何可以具有相同的名称



我不知道这是一个愚蠢的问题,还是可能是comenscence,但我的问题是我正在创建一个包含添加方法的链表类

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));
}
}

遵循以上评论中的好建议。然而,对于任何其他来这里寻找答案的新学习者,我在下面给出了addFirst()方法中要做的更正,如果你没有正确使用块,你需要更改其他函数。尝试将类重命名为Node,并将源文件重命名为Node.java

public void addFirst(int data)
{
node node = new node(data);
if (head == null) 
{
//this is the first ever node, set the head & tail
head = node;
tail = node;
}
else
{   
//place the below lines of code together in a block
node.next = head;
head = node;
}
currentSize++;
}

相关内容

  • 没有找到相关文章

最新更新