为什么我的insertLast(T data)
方法不能将所有元素添加到列表中?
public class Tester {
public static void main(String[] args){
LinkedList<Integer> myList = new LinkedList<Integer>();
myList.insertLast(1);
myList.insertLast(2);
myList.insertLast(3);
myList.insertLast(4);
myList.insertLast(5);
myList.insertLast(6);
myList.displayList();
}
}
它只添加6.代码有什么问题?
public class Node<T> {
public T data;
public Node<T> next;
public Node(T data, Node<T> n){
this.data = data;
this.next = n;
}
public void display(){
System.out.print(this.data + " ");
}
}
class LinkedList<T> implements Iterable<T>{
private Node<T> head;
private int size;
public LinkedList(){
this.head = new Node<T>(null, null);
this.size = 0;
}
public boolean isEmpty(){
return (head.next == null);
}
public void displayList(){
Node<T> current = head;
while(current != null){
current.display();
current = current.next;
}
}
public void insert(T data){
head = new Node<T>(data, null);
size++;
}
public void insertLast(T data){
Node<T> newNode = new Node<T>(data, null);
if(isEmpty()){
head = new Node<T>(data, null);
size++;
}
else{
Node<T> current = head;
while(current.next != null){
current = current.next;
}
current.next = newNode;
size++;
}
}
}
答案 0 :(得分:1)
每次致电insertLast
时,isEmpty
都会返回true,因为head.next
为null
。如果head.next
返回false,则isEmpty
仅设置为非null。
答案 1 :(得分:0)
此检查:
if(isEmpty()){
head = new Node<T>(data, null);
size++;
}
将head初始化为下一个null
,因此isEmpty()每次被调用时都返回true。你需要在isEmpty()
和你的构造函数中检查head本身是否为null,而不是:
this.head = new Node<T>(null, null);
你应该把它初始化为:
this.head = null;
答案 2 :(得分:0)
Hai Minor改变你的程序。你不必将head.next初始化为null
import java.util.Iterator;
import java.util.Spliterator;
import java.util.function.Consumer;
public class Node<T> {
public T data;
public Node<T> next;
public Node(T data, Node<T> n){
this.data = data;
this.next = n;
}
public void display(){
System.out.print(this.data + " ");
}
}
class LinkedList<T> implements Iterable<T>{
private Node<T> head;
private int size;
public LinkedList(){
// this.head = new Node<T>(null, null);
this.size = 0;
}
public boolean isEmpty(){
return (head == null);
}
public void displayList(){
Node<T> current = head;
while(current != null){
current.display();
current = current.next;
}
}
public void insert(T data){
head = new Node<T>(data, null);
size++;
}
public void insertLast(T data){
Node<T> newNode = new Node<T>(data, null);
if(isEmpty()){
head = new Node<T>(data, null);
size++;
}
else{
Node<T> current = head;
while(current.next != null){
current = current.next;
}
current.next = newNode;
size++;
}
}
public void forEach(Consumer<? super T> arg0) {
// TODO Auto-generated method stub
}
public Iterator<T> iterator() {
// TODO Auto-generated method stub
return null;
}
public Spliterator<T> spliterator() {
// TODO Auto-generated method stub
return null;
}
}