我正在尝试重新研究数据结构中包含链接列表的几个主题。因为我的最后一堂课工作太久了,不幸的是,我不确定我的代码有什么问题。请给我一些建议如何解决这个问题,如下所示。将整数添加到LInked List中
LinkedList.java
package my.linked.list;
public class LinkedList<E> {
private Listnode<E> items;
private Listnode<E> lastNode;
int numItems;
public LinkedList() {
items = new Listnode<E>(null);
lastNode = new Listnode<E>(null);
numItems = 0;
}
public void add(E d) {
//Listnode<E> temp = new Listnode<E>(d);
//lastNode.setNext(temp);
lastNode.setNext(new Listnode<E>(d));
lastNode = lastNode.getNext();
numItems++;
}
//public void add(int pos){
//
//}
public void remove(Listnode<E> n) {
Listnode<E> temp = items;
if (items == n) {
items = n.getNext();
}
while (temp.getNext() != n) {
temp = temp.getNext();
}
temp.setNext((n.getNext()));
numItems--;
}
//public void remove(int pos) {
//
//}
public boolean isEmpty() {
boolean ans = false;
if (numItems == 0) {
ans = true;
}
return ans;
}
public boolean contains() {
return false;
}
public int size() {
return numItems;
}
}
MyLinkedListTest.java
package my.linked.list;
import java.io.*;
public class MyLinkedListTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
LinkedList myTest = new LinkedList();
// check whether the linkedlist is empty or not
boolean ans = false;
ans = myTest.isEmpty();
if (ans = true) {
System.out.println("This Linked List is empty");
} else {
System.out.println("This Linked List is not empty");
}
// add operation
for (int i=0; i<5; i++){
myTest.add(i);
System.out.println(myTest);
}
System.out.println("Current size of myList : " + myTest.size());
}
}
当运行该代码时,收到以下消息。
这个链表是空
[email protected]
[email protected]
[email protected]
[email protected]
[email protected]
Current size of myList : 5
它看起来像我的代码不会增加整数值到LinkedList的数据类型。请让我知道如何解决这个问题。非常感谢提前。
请学习如何调试Java代码(例如:使用eclipse) – gerrytan
有什么问题?您打印清单,而不是其内容。 –