I am having some trouble understanding why the function delete() below works for deleting a node in a linked list. I abridged the rest of the code to make this all easier to read.
So, I understand we have a node first with a bunch of nodes linked to first. I also understand that in the delete() function, we need to create a new node n to traverse the list. Here's my hang up:
If we create a new node n, and set n = first, we've created a new node, and the node constructor defines that n will have a new node n.next as well. So, haven't we created a whole new list, separate from the list that begins with first? When the delete() function gets to the point where it sets n.next = n.next.next, isn't that deleting a node in a whole separate list of n nodes? How does this delete the node that is linked off of first? Conceptually, this is my hang up.
How are we actually deleting the node in the list that begins with first?
Edit: I think maybe I answered my own question but I was hoping someone could verify. Does this work because both the first and n nodes are actually just references back to the New Node() object created in the Add() function? When I learned programming it was with C++ so I'm used to seeing pointers, and this code didn't make much sense; but as I understand it Java doesn't explicitly have pointers... so am I correct about all of this?
public class LinkedList { static class Node { public Node() { } public double item; public Node next; } int N; Node first; public LinkedList () { first = null; N = 0; public void delete (int k) { if (k == 0) { first = first.next; N--; } else { Node n = first; for (int i = 0; i < k-1; i++) { n = n.next; } n.next = n.next.next; N--; } } public void add (double item) { Node newfirst = new Node (); newfirst.item = item; newfirst.next = first; first = newfirst; N++; } private static void testDelete () { MyLinked b = new MyLinked (); b.add (1); print ("singleton", b); b.delete (0); print ("deleted", b); for (double i = 1; i < 13; i++) { b.add (i); } print ("bigger list", b); b.delete (0); print ("deleted at beginning", b); b.delete (10); print ("deleted at end", b); b.delete (4); print ("deleted in middle", b); } public static void main (String args[]) { testDelete(); } }