LinkedList Java遍历和打印 [英] LinkedList Java traverse and print

查看:786
本文介绍了LinkedList Java遍历和打印的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您能帮忙回答这个问题,我将非常感激:

I would really appreciate if you can help to answer to this question:

我已经使用Java以非常标准的方式创建了自定义链表。以下是我的课程:

I have already created a custom linked list myself in a very standard way using Java. Below are my classes:

public class Node {

   private Object obj;
   private Node next;

   public Node(Object obj){
       this(obj,null);
   }

   public Node(Object obj,Node n){
       this.obj = obj;
       next = n;
   }

   public void setData(Object obj){
       this.obj = obj;
   }

   public void setNext(Node n){
       next = n;
   }

   public Object getData(){
       return obj;
   }

   public Node getNext(){
       return next;
   }

}




public class linkedList {
    private Node head;


    public linkedList(){
        head = null;
    }

    public void setHead(Node n){
        head = n;
    }

    public Node getHead(){
        return head;
    }


   public void add(Object obj){
       if(getHead() == null){
           Node tmp = new Node(obj);
           tmp.setNext(getHead());
           setHead(tmp);
       }else{
           add(getHead(),obj);
       }
   }


   private void add(Node cur,Object obj){
       if(cur.getNext() == null){
           Node tmp = new Node(obj);
           tmp.setNext(cur.getNext());
           cur.setNext(tmp);
       }else{
           add(cur.getNext(),obj);
       }
   }


}

我试图打印我已插入列表中的值,如下所示

Im trying to print value i have inserted into the list as below

public static void main(String[] args) {
        // TODO code application logic here
        Node l = new Node("ant");
        Node rat = new Node("rat");
        Node bat = new Node("bat");
        Node hrs = new Node("hrs");

        linkedList lst = new linkedList();
        lst.add(l);
        lst.add(rat);
        lst.add(bat);
        lst.add(hrs);



        Node tmp = lst.getHead();
        while(tmp != null){

            System.out.println(tmp.getData());
            tmp = tmp.getNext();

        }


    }

但我从IDE获得的输出是

but the output i got from the IDE is

linklist.Node@137bd6a1
linklist.Node@2747ee05
linklist.Node@635b9e68
linklist.Node@13fcf0ce

为什么打印出来引用但不是字符串的实际值,如bat,ant,rat ...?

why does it print out the reference but not the actual value of the string such as bat,ant,rat... ?

如果我想打印出实际值,那我应该怎么做?

If i want to print out the actual value then what should i do?

非常感谢

推荐答案

您的 linkedList 类已经为你创建节点了!

Your linkedList class already creates the Nodes for you!

linkedList list = new linkedList();
list.add("foo");
list.add("bar");
Node tmp = lst.getHead();
while(tmp != null){
    System.out.println(tmp.getData());
    tmp = tmp.getNext();
}

将打印

foo
bar

这篇关于LinkedList Java遍历和打印的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆