Domanda

So I've been studying for an upcoming java exam, and I came across something I never quite understood. If someone could explain it to me, I would very much appreciate it.

Okay, the problem I'm having is with understanding why the following AddToEnd method works. It just seems to me that all temp is is an IntNode representing the final element in the list, so why is it that by modifying temp somehow the original list is changed? Thanks in advance for your help!

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;
    }
  }
}
È stato utile?

Soluzione

It just seems to me that all temp is is an IntNode representing the final element in the list

I suspect you realise that this is your mistake but it is a difficult concept to grasp.

In fact temp points at (or more accuately refers to) the final element in the list.

At the point when the code says temp.next = newNode you are therefore actually making the next reference of the last entry in the list point to the new entry - which is exactly what you want.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top