您好我正在实现单链表,而不使用库。我在列表末尾添加元素时遇到了问题。任何人都可以帮助我。这是我的代码:
public class SinglyLinkedList<T> implements GenericLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private int size;
public SinglyLinkedList() {
head = null;
tail = null;
size = 0;
}
public void addLast(T elem) {
tail.next.element = elem;
size++;
}
**public void addLast(T elem) {
Node<T> newNode = new Node<T>();
tail.next = null;
newNode.element = elem;
**
答案 0 :(得分:2)
指定尾部的下一个元素,但您还应该考虑插入的元素本身成为新的尾部。简而言之:
nth - 1
元素)。您当前的问题也与步骤1和3有关。您没有定义要存储的Node
对象,如果它真的是列表的尾部,则tail.next
应为null。
答案 1 :(得分:1)
这里是singlylinkedlist的完整代码 的 SinglyLinkedList 强>
public class SinglyLinkedList<T> {
private Node<T> head;
private Node<T> tail;
private Node<T> temp;
private int size;
public SinglyLinkedList() {
head = null;
tail = null;
size = 0;
}
public void addLast(T elem) {
if(head == null){
head = new Node<T>();
head.element = elem;
tail = head;
size++;
} else {
temp = new Node<T>();
temp.element = elem;
tail.next = temp;
temp.prev = tail;
tail = temp;
size++;
}
}
void print(){
temp = head;
while(temp != null){
System.out.println(temp.element);
temp = temp.next;
}
}
public static void main(String[] args) {
SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
list.addLast(1);
list.addLast(2);
list.addLast(3);
list.addLast(4);
list.addLast(5);
list.addLast(6);
list.print();
}
}
<强>节点强>
public class Node<T>{
Node<T> prev;
Node<T> next;
T element;
public Node() {
}
}