【问题标题】:removing from a linked list从链表中删除
【发布时间】:2013-05-17 13:07:28
【问题描述】:

我创建了一个SListClass,它代表单链表类和一个节点类SListNode。我遇到了removeLast 方法的问题。当我打印出节点列表时,第一项仍然存在。我不明白为什么

public class SListClass {
    private SListNode head;
    private double size;

    SListClass(){
        head = null;
        size = 0;
    }
    SListClass(SListNode node){
        head = node;
    }

    public void insertFront(int item){
        head = new SListNode(item, head);
        size++;
    }

    public void addLast(SListNode head, int value){
        SListNode first = head;
        while(first.next != null){
            first = first.next;
        }
        first.next = new SListNode(value, null);
        size++;
    }

    public void removeFirst(SListNode head){
        head = head.next;
    }

    /*public String toString(){
        return String.format(head + "");
    }
    */
    public String  print(){
        String result = head.item + " ";

        if(head.next != null){
            result += head.next.print();
        }
        return result;
    }
    public static void main(String[] args) {

        SListNode list = new SListNode(21, new SListNode(5, new SListNode(19, null)));
        SListClass x = new SListClass(list);

        x.insertFront(33);
        x.insertFront(100);
        x.addLast(list, 123);
        x.addLast(list, 9999);
        x.removeFirst(list);
        System.out.println(x.print());

    }
 }

output: 100 33 21 5 19 123 9999

SListNode 类:

public class SListNode {            
    protected int item;
    protected SListNode next;

    public SListNode(int item, SListNode next){
        this.item = item;
        this.next = next;
    }

    public SListNode(int item){
        this(item, null);
    }

    public int getItem() {
        return item;
    }

    public void setItem(int item) {
        this.item = item;
    }

    public SListNode getNext() {
        return next;
    }

    public void setNext(SListNode next) {
        this.next = next;
    }
   }

【问题讨论】:

    标签: java singly-linked-list


    【解决方案1】:

    removeFirst 更改为this.head = head.next。参数列表中的head隐藏了类字段head

    另外,考虑一下:在removeFirst 方法中,您真的需要head 参数,还是应该使用head 字段,因为这是您尝试更新的链表的真正头部?如果您不再需要该参数,只需从方法签名中删除该参数即可;那么head 字段没有隐藏,所以head = head.next 就可以了。

    【讨论】:

    • 非常感谢,我没想到隐藏会导致这个问题
    【解决方案2】:

    首先,你的命名不好。每个类都是一个类,所以以Class 结尾的类名只是噪音。相反S 没有任何意义。如果一定要说明SListClass代表什么,那就说明名字不好,应该换个名字,不需要解释,比如SinglyLinkedList

    您班级的用户不应该关心列表如何保留信息。它永远不必将节点传递给任何方法。只有一个值。所以应该修改以下方法:

    • SListClass(SListNode node) --> SinglyLinkedList(int value)
    • void addLast(SListNode head, int value) --> void addLast(int value) :列表知道头节点是什么。将它作为参数传递是没有意义的。
    • void removeFirst(SListNode head) --> void removeFirst() :列表知道第一个节点是什么。将其作为参数传递是没有意义的

    一旦你得到了正确的 API,你会发现一切都会更容易弄清楚,因为你不会混淆列表的实际头部和作为参数传递的不必要的头部。

    【讨论】:

      猜你喜欢
      • 2018-10-14
      • 2020-10-29
      • 2013-01-08
      • 1970-01-01
      • 1970-01-01
      • 2017-10-21
      相关资源
      最近更新 更多