使用尾引用Java在列表末尾插入节点的方法

时间:2020-12-12 07:19:13

I am currently trying to write a method insertEnd that inserts a node at the end of a list, using the tail reference. As I am still learning about it, I do not know how I can approach this. If you have any suggestions or solutions, please could you let me know as it will help me greatly.

我目前正在尝试编写一个方法insertEnd,它使用尾部引用在列表的末尾插入一个节点。由于我还在了解它,我不知道如何处理这个问题。如果您有任何建议或解决方案,请告诉我,因为它对我有很大的帮助。

package lib;

public class LinkedList {
private Node head;
private Node tail;

public LinkedList(Node h){
    head = h;
}
public Node getHead(){
    return head;
}
public Node getTail(){
    return tail;
}

public void setHead(Node n){
    head = n;
}

    public void insertEnd(Node newNode){

    }
public class ListApp {

    public static void main(String[] args){
        Node n4 = new Node("green", null);
        Node n3 = new Node("orange", n4);
        Node n2 = new Node("blue", n3);
        Node n1 = new Node("red", n2);





package lib;

public class Node {
private String item;
private Node nextItem;

public Node(String str, Node n){
    item = str;
    nextItem = n;
}
public String getItem(){
    return item;
}
public void setItem(String str){
    item = str;
}
public Node next(){
    return nextItem;
}
public void setNext(Node n){
    nextItem = n;
}

public String getHead(){
    return item;
}
}

2 个解决方案

#1


1  

Here's one possible solution:

这是一个可能的解决方案:

public void insertEnd(Node newNode){
    newNode.setNext(null);
    if (tail == null) {
        tail = newNode;
        head = newNode;
    } else {
        tail.setNext(newNode);
        tail = newNode;
    }
}

#2


0  

Assuming your Node, holds a reference to next,

假设您的Node,保留对next的引用,

public class Node<E>{
  private E ele;
  private Node<E> next;

P.S: Java already does have the LinkedList implemented for our convenience.

P.S:为了方便起见,Java已经实现了LinkedList。

#1


1  

Here's one possible solution:

这是一个可能的解决方案:

public void insertEnd(Node newNode){
    newNode.setNext(null);
    if (tail == null) {
        tail = newNode;
        head = newNode;
    } else {
        tail.setNext(newNode);
        tail = newNode;
    }
}

#2


0  

Assuming your Node, holds a reference to next,

假设您的Node,保留对next的引用,

public class Node<E>{
  private E ele;
  private Node<E> next;

P.S: Java already does have the LinkedList implemented for our convenience.

P.S:为了方便起见,Java已经实现了LinkedList。