【问题标题】:Updating the head node automatically after inserting new node at the beginning of the linked list in java在java中的链表开头插入新节点后自动更新头节点
【发布时间】:2021-11-12 09:04:15
【问题描述】:

我有这个添加新节点到我的链表的代码,我想在链表的开头添加新节点,我在插入函数上写了这个代码,

Node insert(Node start, int x){
    Node newNode = new Node(x);
    if(start == null) {
        return start = newNode;
    } else {
        newNode.next = start;
        start = newNode;
    }
    return start;
}

这是我的主要课程,有没有其他方法可以更有效地做到这一点?

LinkedList list=new LinkedList();
Node startPoint=new Node(20);  
Node newNode=list.insert(startPoint, 16);
Node newNode1=list.insert(newNode, 22);
Node newNode2=list.insert(newNode1, 2);
Node newNode3=list.insert(newNode2, 5);
Node newNode4=list.insert(newNode3, 44);
Node newNode5=list.insert(newNode4, 77);

【问题讨论】:

  • 当您说高效时,您是指执行时间?我对此表示怀疑。真的没有太多事情发生。就个人而言,我会跳过第一个分支中的return 部分。它清楚地表明start 始终返回,无论采用哪个分支。
  • 你的意思是 if 部分?

标签: java data-structures linked-list


【解决方案1】:

这是我的主要课程,有没有其他方法可以更有效地做到这一点?

没有。
这是解决此问题的classical

之所以不能做得更好,是因为这个操作的实现需要O(1)时间。这真的很酷很性感,因为执行它的时间不取决于输入的大小,这对于大型数据集来说是一个非常酷的属性。

您可以通过使用链表实现更复杂的操作来继续锻炼您的 DS 技能,例如插入到链表中的任意位置或反转链表。

【讨论】:

    【解决方案2】:

    效率还可以,但你可以让它更优雅。

    首先,您的主程序不必知道节点。它应该只需要创建链表实例,并向其中添加整数。您的主代码现在维护一些 state(如 startPoint),实际上链表实例应该为您管理这些状态。它应该维护对其列表中第一个节点的引用(以null 开头):通常称为head

    由于您写了 “...想要在列表的开头添加新节点”,因此您不需要将节点作为参数传递给 insert。链接的实例可以使用其head 成员在其之前进行插入,然后更新其head 以引用该新节点。 insert 方法也应该不需要返回新创建的节点。调用者不必担心此类实现细节。

    最后,您可以添加一个 Node 构造函数重载,该重载接受对其next 成员的引用。这将有助于使您的 insert 方法非常简洁。

    所以,让您的 Node 构造函数像这样(我假设 value 成员称为 value,如果您使用不同的名称,例如 data,请根据需要进行调整):

    class Node {
        private final int value;
        private Node next;
    
        public Node(int value) {
            this.value = value;
            this.next = null;
        }
    
        public Node(int value, Node next) {
            this.value = value;
            this.next = next;
        }
    
        /* ... other methods */
    }
    

    然后在您的链表类中,确保您有一个 head 成员,并定义您的 insert 方法,使其只接受一个值参数:

    public class LinkedList {
        private Node head;
    
        public LinkedList() {
            this.head = null;
        }
    
        void insert(int x) {
            head = new Node(x, head);
        }
    
        /* other methods ... */
    }
    

    然后你的主程序可以做:

        LinkedList list = new LinkedList();
        list.insert(20);
        list.insert(16);
        list.insert(22);
        list.insert(2);
        /* ...etc... */
    

    当然,您需要添加允许您从列表中检索值并对其执行其他有趣操作的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-05
      • 1970-01-01
      • 2010-12-31
      • 1970-01-01
      相关资源
      最近更新 更多