简体   繁体   English

实现toString方法以打印出LinkedList

[英]Implementing a toString method to print out a LinkedList

I'm having trouble with a project I have for my OOP class. 我的OOP课程项目有问题。 I'm nearly finished, but still lack a toString method and a main method. 我差不多完成了,但仍缺少toString方法和主要方法。 Not really sure how to go about it and would appreciate any help. 不确定如何去做,并希望得到任何帮助。 I want my toString method to function as follows: 我希望我的toString方法的功能如下:

Returns a string representation of all the items stored in the list. 返回列表中存储的所有项的字符串表示形式。 A string representation of an empty list looks like head--><--tail A string representation of a non-empty list looks like: head-->134<-->-8<-->42<-->1<--tail 空列表的字符串表示形式类似于head--><--tail非空列表的字符串表示形式如下: head-->134<-->-8<-->42<-->1<--tail

public class IntegerNode{

    private IntegerNode next;
    private IntegerNode prev;
    private int data;

    public IntegerNode(int data){
        next = next; 
        prev = prev;
        data = data;     
    }

    public int getData(){
        data = data;
        return this.data;   
    }

    public IntegerNode getNext(){
        return next;
    }

    public IntegerNode getPrevious(){
        return prev;
    }

    public void setNext(IntegerNode in){
        prev = in;
    }

    public void setPrevious(IntegerNode in){
        prev = in;
    }

}

and here is what I have so far in my IntegerLinkedList class 这是我目前在IntegerLinkedList类中的内容

public class IntegerLinkedList{

    private IntegerNode head;
    private IntegerNode tail;

    public IntegerLinkedList(){
        head = null;
        tail = null;
    }

    public void addFirst(int x){
        IntegerNode nH = new IntegerNode(x);
        if (head == null) {
            head = nH;
            tail = nH;
        }else{
            head.setPrevious(nH);
            nH.setNext(head);
            head = nH;

        }
    }

    public void addLast(int x){
        IntegerNode t = new IntegerNode(x);
        if (tail == null){
            head = t;
            tail = t;
        }else{
            tail.setNext(t);
            t.setPrevious(tail);
            tail = t;
        }
    }

    public int peekFirst(){
        return head.getData();
    }

    public int peekLast(){
        return tail.getData();
    }

    public String toString(){
        if (head == null && tail == null){
            String empty = "head--><--tail";
            return empty;
        }else{
            String h = "Head--> " + head;
            String t = tail + " <--Tail";
            String m = " <--> ";
           // while(IntegerNode.getNext() != null) 
           //}
           //return h + m + t;

        }
    }

    public int pollFirst(){
        int x = head.getData();
        head = head.getNext();
        head.setPrevious(null);
        return x;
    }

    public int pollLast(){
        int x = tail.getData();
        tail = tail.getPrevious();
        tail.setNext(null);
        return x;
    }

}

I'm thinking a while loop is the way to go here, but then again I'm not sure. 我想有一段时间循环就是去这里的方式,但是我又不确定了。

Here's how to write it: 以下是编写它的方法:

@Override  // <-- Annotate that you are overriding the toString() method
public String toString(){
    if (head == null && tail == null){
        String empty = "head--><--tail";
        return empty;
    }else{
       StringBuilder sb = new StringBuilder();
       sb.append("Head-->");

       IntegerNode curr = head;
       sb.append(curr.getData());
       curr = curr.getNext();
       while(curr != null) {
           sb.append("<-->");
           sb.append(curr.getData());
           curr = curr.getNext();
       }
       sb.append("<--tail");
       return sb.toString();
    }
}

As an alternative, you can simplify the logic to not have an outer if else: 作为替代方案,您可以将逻辑简化为不具有外部if else:

@Override  // <-- Annotate that you are overriding the toString() method
public String toString(){
   StringBuilder sb = new StringBuilder();
   sb.append("Head-->");

   IntegerNode curr = head;

   if (curr == null)
   {
      sb.append("<--tail");
      return sb.toString();
   }

   sb.append(curr.getData());
   curr = curr.getNext();
   while(curr != null) {
       sb.append("<-->");
       sb.append(curr.getData());
       curr = curr.getNext();
   }
   sb.append("<--tail");

   return sb.toString();
}

Yes, you have to use a loop, because you want to iterate over data of unknown length. 是的,你必须使用一个循环,因为你想迭代未知长度的数据。 Michael Markidis wrote the answer more quickly than me, use his solution, however I would suggest some improvements to your code. 迈克尔Markidis比我更快地写了答案,使用他的解决方案,但我会建议你的代码有一些改进。

String h = "Head--> " + head; won't work, because head is an object IntegerNode , and you want to access its data like this head.getData() (also why do you assign data = data; in this method? It should only do return) 不会工作,因为head是一个IntegerNode对象,并且你想要访问它的数据,比如head.getData() (为什么你要分配data = data;在这个方法中?它应该只返回)

If you want to assign data in constructor that have the same name as field, use have to use this keyword to make clear what do you want to assign. 如果要在构造函数中分配与字段具有相同名称的数据,请使用this关键字来明确要分配的内容。 Also assigning null next and prev has no meaning, so this code 同时指定null nextprev也没有意义,所以这段代码

public IntegerNode(int data){
    next = next; 
    prev = prev;
    data = data;     
}

should look like this 应该是这样的

public IntegerNode(int data){
    this.data = data;     
}

or if you want to assign the previous and next node 或者如果要分配上一个和下一个节点

public IntegerNode(int data, IntegerNode next, IntegerNode prev){
    this.next = next; 
    this.prev = prev;
    this.data = data;     
}

If you are using Java 8+, StringJoiner makes it easy. 如果您使用的是Java 8+, StringJoiner可以轻松实现。

@Override
public String toString() {
    StringJoiner joiner = new StringJoiner("<-->", "head-->", "<--tail");
    for (IntegerNode node = this.head; node != null; node = node.getNext())
        joiner.add(String.valueOf(node.getData()));
    return joiner.toString();
}

If not using Java 8, a StringBuilder is the right way to go. 如果不使用Java 8, StringBuilder是正确的方法。
(Performs better than using String directly) (执行比直接使用String更好)

@Override
public String toString() {
    StringBuilder buf = new StringBuilder("head-->");
    boolean sep = false;
    for (IntegerNode node = this.head; node != null; node = node.getNext()) {
        if (sep)
            buf.append("<-->");
        buf.append(node.getData());
        sep = true;
    }
    return buf.append("<--tail").toString();
}

In both cases, you use a basic for loop with a node variable to iterate through the list. 在这两种情况下,您都使用带有node变量的基本for循环来遍历列表。


As for the rest of your code, you have some issues. 至于你的其余代码,你有一些问题。

 public IntegerNode(int data){ next = next; prev = prev; data = data; } 

Assigning next to next and prev to prev is meaningless. 分配nextnext ,并prevprev是没有意义的。
Assigning the parameter to the field will only work if you qualify the field with this. 将参数分配给字段仅在您使用this.字段限定字段时才有效this. , otherwise you're assigning the parameter to itself (meaningless). ,否则你将参数分配给自己(无意义)。

public IntegerNode(int data){
    this.data = data;     
}

 public int getData(){ data = data; return this.data; } 

Assigning data to data is meaningless. data分配给data毫无意义。

public int getData(){
    return this.data;   
}

 public void setNext(IntegerNode in){ prev = in; } 

Copy/paste error. 复制/粘贴错误。 You meant to assign to next . 你打算分配到next

public void setNext(IntegerNode in){
    next = in;
}

 public int pollFirst(){ int x = head.getData(); head = head.getNext(); head.setPrevious(null); return x; } public int pollLast(){ int x = tail.getData(); tail = tail.getPrevious(); tail.setNext(null); return x; } 

These methods will throw NullPointerException when you poll the last 1 value from the list. 从列表中轮询最后1个值时,这些方法将抛出NullPointerException
Add missing if statement. 添加缺少的if语句。

public int pollFirst(){
    int x = head.getData();
    head = head.getNext();
    if (head == null)
        tail = null;
    else
        head.setPrevious(null);
    return x;
}

public int pollLast(){
    int x = tail.getData();
    tail = tail.getPrevious();
    if (tail == null)
        head = null;
    else
        tail.setNext(null);
    return x;
}

1) "last" refers to the "only remaining" value, not the "tail" value. 1)“最后”是指“仅剩余”值,而不是“尾部”值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM