【问题标题】:How to modify the head of a LinkedList without a wrapper class?如何在没有包装类的情况下修改 LinkedList 的头部?
【发布时间】:2021-04-14 03:51:17
【问题描述】:

当我创建一个 Node 对象并调用“appendToTail”时,Node 对象通过 next 属性(如预期的那样)具有一系列节点。我尝试创建一个弹出窗口,它获取头部(又名“this”)并用变量引用它并用它的下一个覆盖它。但是,“this”与原来的头像相同。我做错了什么,或者没有办法修改'this'?

public class Node {
    Node next = null;
    int data;

    public Node(int d) {
        data = d;
    }

    public void appendToTail(int d) {
        Node end = new Node(d);
        Node n = this;
        while (n.next != null) {
            n = n.next;
        }
        n.next = end;
    }

    public void popHead() {
        Node n = this;
        n = n.next;
        
    }
}

【问题讨论】:

  • 您不能修改this。它总是指一个给定的对象。 Node 本身不应该知道 Head 是什么。应该有一个 List 类来保存关于头部是什么的信息,你应该修改它。
  • 你想实现先进先出队列之类的东西吗?
  • this 是一个关键字,而不是一个变量。它让我们获得对 current 对象的引用,但它不允许我们修改 该引用。无论如何,您为什么首先要这样做?这感觉就像XY problem
  • 我想你可以用节点 2 的数据替换 head 中的数据,将 head 的引用设置为节点 2 的引用,然后删除节点 2。虽然这会很复杂,但并不理想,我只会使用包装器
  • 谢谢大家!我正在阅读Cracking the Coding Interview,他们以这个为例,并提到如果其他对象引用了这个节点,如果它被替换,他们仍然会引用旧的头......我感到困惑的是,在这个例子中,如何你能换个头吗?我能想到的唯一方法是使用包装器列表类。

标签: java linked-list singly-linked-list


【解决方案1】:

基本上你需要构建一个自定义的 List 并在 End 处添加每个节点。此外,您还需要存储第一个节点以获得循环的起点。

public class NodeList
{
    Node head=null;
    
    public static void main(String args[])
    {
        NodeList nl = new NodeList();
        nl.addNode(1);
        nl.addNode(2);
        nl.addNode(3);
        nl.listNodes();
    }
    
    public void addNode(int data)
    {
        if(head==null)
        {
            head = new Node(data);
        }
        else
        {
            Node curent = head;
            while(curent.next != null)
            {
                curent = curent.next;       
            }
            curent.next = new Node(data);
        }
    }
    
    public void listNodes()
    {
        if(head !=null)
        {
            Node curent = head;
            System.out.println(curent.data);
            while(curent.next !=null)
            {
                curent = curent.next;
                System.out.println(curent.data);
            }
        }
    }
    
    class Node 
    {
        Node next = null;
        int data;

        public Node(int d) {
            data = d;
        }
    }
}

输出

1
2
3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-11-03
    • 2018-08-19
    • 1970-01-01
    • 2019-08-17
    • 2021-10-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多