[英]Java Linked List, don't understand
所以我一直在為即將到來的 Java 考試而學習,我遇到了一些我從未完全理解的東西。 如果有人可以向我解釋,我將不勝感激。
好的,我遇到的問題是理解為什么下面的 AddToEnd 方法有效。 在我看來,所有 temp 都是一個 IntNode 表示列表中的最后一個元素,那么為什么通過修改 temp 以某種方式更改了原始列表? 在此先感謝您的幫助!
public class IntList {
private IntNode front; //first node in list
//-----------------------------------------
// Constructor. Initially list is empty.
//-----------------------------------------
public IntList() {
front = null;
}
//-----------------------------------------
// Adds given integer to front of list.
//-----------------------------------------
public void addToFront(int val) {
front = new IntNode(val,front);
}
//-----------------------------------------
// Adds given integer to end of list.
//-----------------------------------------
public void addToEnd(int val) {
IntNode newnode = new IntNode(val,null);
//if list is empty, this will be the only node in it
if (front == null)
front = newnode;
else {
//make temp point to last thing in list
IntNode temp = front;
while (temp.next != null)
temp = temp.next;
//link new node into list
temp.next = newnode;
}
}
//*************************************************************
// An inner class that represents a node in the integer list.
// The public variables are accessed by the IntList class.
//*************************************************************
private class IntNode {
public int val; //value stored in node
public IntNode next; //link to next node in list
//------------------------------------------------------------------
// Constructor; sets up the node given a value and IntNode reference
//------------------------------------------------------------------
public IntNode(int val, IntNode next) {
this.val = val;
this.next = next;
}
}
}
在我看來,所有 temp 都是一個 IntNode,代表列表中的最后一個元素
我懷疑您意識到這是您的錯誤,但這是一個難以掌握的概念。
實際上 temp指向(或更准確地說是指)列表中的最后一個元素。
當代碼顯示temp.next = newNode
您實際上是在將列表中最后一個條目的next
引用指向新條目 - 這正是您想要的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.