简体   繁体   English

链表 addLast 方法

[英]Linked list addLast method

How can I build an addLast method in Java?如何在 Java 中构建addLast方法? I already know LinkedList has a built-in method which does this)我已经知道LinkedList有一个内置的方法可以做到这一点)

This is what I've tried:这是我尝试过的:

public void addFirst(int d1, double d2) { 
    Link link = new Link(d1, d2); 
    link.nextLink = first; 
    first = link;
        }
public void addLast(int d1 , double d2){
    Link v = new Link(d1, d2);
    v.nextLink = null;
    tail.nextLink = v;
   tail = v  

} }

    public void printList() { 
    Link currentLink = first; 
    System.out.print("List: "); 
    while(currentLink != null) { 
    currentLink.printlink(); 
    currentLink = currentLink.nextLink; 
    } 
        System.out.println(""); 
}

My addFirst method works, but I don't know how to connect them.我的addFirst方法有效,但我不知道如何连接它们。

in the main:主要是:

    LinkList list = new LinkList();  
         list.addFirst(4, 4.04); 
         list.addFirst(5, 5.05); 
         list.addlast(3,4.5);
         list.printList();

I realize that this is a school assignment so without giving the answer here are the steps to follow:我意识到这是一项学校作业,因此在不给出答案的情况下,请遵循以下步骤:

  1. check if list is empty检查列表是否为空
  2. if list is empty set head + tail to point to same node如果列表为空,则设置 head + tail 指向同一个节点
  3. Iterate over all elements遍历所有元素
  4. Update tail to new node将尾部更新到新节点

Also there is no way that the addFirst method you have above would work you are constantly resetting the value in tail.此外,您上面的 addFirst 方法也无法正常工作,您会不断地重置尾部的值。

Your problem appears to be in the last line.您的问题似乎在最后一行。 You want你要

tail = v;

Not不是

v = tail;

Furthermore, You have此外,您有

tail = link

as the last line of your addFirst method - it's not clear why you're doing this.作为 addFirst 方法的最后一行 - 目前尚不清楚您为什么要这样做。 You shouldn't need to update the tail of the list as you add to the front.在添加到前面时,您不需要更新列表的尾部。

public void addLast(int d1, double d2){

    Node node = new Node(d1, d2);
    Node temp = first;
    while(temp.next!= null) {
        temp = temp.next;
    }
    temp.next = node;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM