好的,所以我正在尝试学习如何打印出链接列表。我拥有列表需要使用的所有方法,但我不知道如何显示节点的值。现在我的 main 方法中没有任何内容,因为我在尝试调用 main 中的非静态方法时不断出错。我有一个显示列表内容的 toString 方法。我将如何调用这个 toString 来显示每个节点的值?任何建议将不胜感激。
这是节点类:
public class LinkedListNode
{
private int data;
private LinkedListNode next;
public LinkedListNode(int data)
{
this.data = data;
this.next = null;
}
public int getData()
{
return data;
}
public void setData(int d)
{
data = d;
}
public LinkedListNode getNext()
{
return next;
}
public void setNext(LinkedListNode n)
{
next = n;
}
}
这是包含操作列表的主要方法和方法的 LinkedList 类:
public class LinkedList {
public LinkedListNode head;
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.insertFront(0);
System.out.println(l.toString());
}
public LinkedList() {
this.head = null;
}
public int removeFront(){
if(head == null){
System.out.println("Error - Attempting to call removeFront() on empty list");
return 0;
}else{
int temp = head.getData();
head = head.getNext();
return temp;
}
}
public void insertFront(int data){
if(head == null){
head = new LinkedListNode(data);
}else{
LinkedListNode newNode = new LinkedListNode(data);
newNode.setNext(head);
head = newNode;
}
}
public void insertBack(int data){
if(head == null){
head = new LinkedListNode(data);
}else{
LinkedListNode newNode = new LinkedListNode(data);
LinkedListNode current = head;
while(current.getNext() != null){
current = current.getNext();
}
current.setNext(newNode);
}
}
public int removeBack(){
if(head == null){
System.out.println("Error - Attempting to call removeBack() on empty list");
return 0;
}else if (head.getNext() == null){
int temp = head.getData();
head = null;
return temp;
}else{
LinkedListNode current = head;
while(current.getNext().getNext() != null){
current = current.getNext();
}
int temp = current.getNext().getData();
current.setNext(null);
return temp;
}
}
public String toString(){
String retStr = "Contents:\n";
LinkedListNode current = head;
while(current != null){
retStr += current.getData() + "\n";
current = current.getNext();
}
return retStr;
}
public LinkedListNode getHead() {
return head;
}
public void setHead(LinkedListNode head) {
this.head = head;
}
}