Java 使用 toString 打印链表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19283083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Printing out a linked list using toString
提问by Shawn
Ok guys, so I am trying to learn how to print out a linked list. I have all the methods that I would need to use for the list, but I can't figure out how to display the values of the nodes. Right now there is nothing in my main method because I kept getting errors trying to call non static methods in the main. I have a toString method that displays the contents of the list. How would I go about calling this toString to display the value of each node? Any advice will be greatly appreciated.
好的,所以我正在尝试学习如何打印出链表。我有我需要用于列表的所有方法,但我无法弄清楚如何显示节点的值。现在我的 main 方法中没有任何内容,因为我一直在尝试在 main 中调用非静态方法时出错。我有一个显示列表内容的 toString 方法。我将如何调用这个 toString 来显示每个节点的值?任何建议将不胜感激。
Here is the node class:
这是节点类:
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;
}
}
Here is the LinkedList class that contains the main and methods to manipulate the list:
这是 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;
}
}
采纳答案by Marin
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
String result = "";
LinkedListNode current = head;
while(current.getNext() != null){
result += current.getData();
if(current.getNext() != null){
result += ", ";
}
current = current.getNext();
}
return "List: " + result;
}
回答by zaerymoghaddam
When the JVM
tries to run your application, it calls your main method statically; something like this:
当JVM
尝试运行您的应用程序时,它会静态调用您的 main 方法;像这样:
LinkedList.main();
That means there is no instance of your LinkedList
class. In order to call your toString()
method, you can create a new instance of your LinkedList
class.
这意味着没有你的LinkedList
类的实例。为了调用您的toString()
方法,您可以创建类的新实例LinkedList
。
So the body of your main
method should be like this:
所以你的main
方法的主体应该是这样的:
public static void main(String[] args){
// creating an instance of LinkedList class
LinkedList ll = new LinkedList();
// adding some data to the list
ll.insertFront(1);
ll.insertFront(2);
ll.insertFront(3);
ll.insertBack(4);
System.out.println(ll.toString());
}
回答by TwentyMiles
As has been pointed out in some other answers and comments, what you are missing here is a call to the JVM System class to print out the string generated by your toString() method.
正如在其他一些答案和评论中指出的那样,您在这里缺少的是对 JVM System 类的调用,以打印出由您的 toString() 方法生成的字符串。
LinkedList myLinkedList = new LinkedList();
System.out.println(myLinkedList.toString());
This will get the job done, but I wouldn't recommend doing it that way. If we take a look at the javadocs for the Object class, we find this description for toString():
这将完成工作,但我不建议这样做。如果我们查看 Object 类的 javadoc,我们会发现 toString() 的描述:
Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representationthat is easy for a person to read. It is recommended that all subclasses override this method.
返回对象的字符串表示形式。通常, toString 方法返回一个“文本表示”此对象的字符串。结果应该是一个简洁但信息丰富的表示,易于人们阅读。建议所有子类都覆盖此方法。
The emphasis added there is my own. You are creating a string that contains the entire state of the linked list, which somebody using your class is probably not expecting. I would recommend the following changes:
强调的是我自己的。您正在创建一个包含链表整个状态的字符串,使用您的类的人可能没有预料到这一点。我建议进行以下更改:
- Add a toString() method to your LinkedListNode class.
- Update the toString() method in your LinkedList class to be more concise.
- Add a new method called printList() to your LinkedList class that does what you are currently expecting toString() to do.
- 将 toString() 方法添加到 LinkedListNode 类。
- 更新 LinkedList 类中的 toString() 方法,使其更加简洁。
- 向 LinkedList 类添加一个名为 printList() 的新方法,该方法执行您当前期望 toString() 执行的操作。
In LinkedListNode:
在 LinkedListNode 中:
public String toString(){
return "LinkedListNode with data: " + getData();
}
In LinkedList:
在链表中:
public int size(){
int currentSize = 0;
LinkedListNode current = head;
while(current != null){
currentSize = currentSize + 1;
current = current.getNext();
}
return currentSize;
}
public String toString(){
return "LinkedList with " + size() + "elements.";
}
public void printList(){
System.out.println("Contents of " + toString());
LinkedListNode current = head;
while(current != null){
System.out.println(current.toString());
current = current.getNext();
}
}
回答by Wiebke
I do it the following way:
我这样做:
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.insertFront(1);
list.insertFront(2);
list.insertFront(3);
System.out.println(list.toString());
}
String toString() {
StringBuilder result = new StringBuilder();
for(Object item:this) {
result.append(item.toString());
result.append("\n"); //optional
}
return result.toString();
}
回答by biniam
A very simple solution is to override
the toString()
method in the Node
. Then, you can call print by passing LinkedList
's head
.
You don't need to implement any kind of loop.
一个非常简单的解决方案是override
在toString()
该方法中Node
。然后,您可以通过传递LinkedList
's来调用 print head
。您不需要实现任何类型的循环。
Code:
代码:
public class LinkedListNode {
...
//New
@Override
public String toString() {
return String.format("Node(%d, next = %s)", data, next);
}
}
public class LinkedList {
public static void main(String[] args) {
LinkedList l = new LinkedList();
l.insertFront(0);
l.insertFront(1);
l.insertFront(2);
l.insertFront(3);
//New
System.out.println(l.head);
}
}