1

我在 java 中遇到了一个概念性的问题。这是我的基本实现LinkedList

节点:

class Node {
  int data;
  Node next = null;

  public Node(int data) {
    this.data = data;   
  } 
}

名单:

class LinkedList {  
  Node n = null;
  Node start = null;
  int flag = 0;

  void insertion(int x) {
    if(flag==0)
    {   
      Node newnode = new Node(x);
      n = newnode;
      start = newnode;
      flag = 1;
      return;
    }

    Node newnode = new Node(x);
    n.next = newnode;
    n = n.next;
  }

  void deletion() {
    Node str = start;
    while(str.next.next != null)
      str = str.next;
    str.next = null;        
  }

  void printlist() {
    Node str = start;
    while(str != null) {
      System.out.println(str.data);
      str = str.next;
    }
  }
}

测试类:

public class Test31 {
  public static void main(String[] args){
    LinkedList ll = new LinkedList();
    ll.insertion(5); 
    ll.insertion(15);
    ll.insertion(25);
    ll.insertion(35);
    ll.insertion(45);
    ll.insertion(55);
    ll.deletion();ll.deletion();
    ll.printlist();
  }
}                       

上面的程序工作得很好,没有任何问题,但是如果我deletion()用这段代码替换:

void deletion() {
  Node str = start;
  while(str.next != null)
    str = str.next;
  str = null;       
}

然后不会删除元素。我有兴趣知道为什么会这样。使用str.next.next确实有诀窍,但如果我使用上面给出的删除方法,它不应该只用一次 while 循环迭代就能达到同样的效果吗?

4

1 回答 1

3

This is because one of the str.next objects still has a reference to it (or potentially start is referencing it). By setting str to null, you are simply setting the local variable in that method to null, but by setting str.next to null, you are deleting the reference in that str object.

Simple example:

Node start = new Node();
Node another = new Node();
start.next = another;
Node toDelete = another;

If you do this:

toDelete = null;

In this case, toDelete is now null. start.next and another still contain references to the object another was originally assigned to. Even if you append this:

another = null;

In this case, there's still one reference left. start.next still points to the original object that another was initially assigned to.

I think the first deletion method is actually incorrect too, as it will never delete the starting node and will throw a NullPointerException if you only have one node in it since start.next is null and the while loop is attempting to get to start.next.next. I think this is more accurate:

void deletion() {
    Node parent = null;
    Node current = start;
    while (current.next != null) {
        parent = current;
        current = current.next;
    }
    if (parent == null) {
        start = null;
        flag = 0;
    } else {
        parent.next = null;
        n = parent;
    }    
}
于 2013-01-15T19:00:29.803 回答