好吧,所以我想學習如何打印出一個鏈表。我有所有需要用於列表的方法,但我無法弄清楚如何顯示節點的值。現在我的主要方法中沒有任何東西,因爲我一直在嘗試調用main中的非靜態方法時出現錯誤。我有一個toString方法來顯示列表的內容。我將如何去調用這個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;
}
}
您創建類的實例,並調用'的toString ()'就可以了。 –
調用'的toString()'方法。我沒有看到任何問題。 – Prateek
你是什麼意思。如果我稱之爲「的toString()」在我的主要方法,我得到的,說:「不能讓一個靜態參考非靜態方法的toString()的錯誤? – Shawn