繁体   English   中英

Java链表,不懂

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM