【问题标题】:deleting a node using a method in Java使用 Java 中的方法删除节点
【发布时间】:2016-11-07 00:12:33
【问题描述】:

我已经找到了 add()print() 方法。现在我想让我的delete()peek() 方法工作。我的代码反复尝试了很多次,我无法弄清楚问题所在。

NodeFN 类:

public class NodeFN {
    private String data; // Data for node.
    private NodeFN next; // Next node.

public NodeFN(String data) {
    this.data = data; // Take the data value passed in & store it in the data field.
    this.next = null; // Take the next node & store it in the next field.
}

// Mutator functions.
   public String getData() {return data;}
   public NodeFN getNext() {return next;}
   public void setData(String d) {data = d;}
   public void setNext(NodeFN n) {next = n;}
}

队列类:

public class Queue {
    NodeFN head = null; // Head of node.
    public String n; // Will be used later.

public Queue(String n) { 
    head = new NodeFN(n); // head is now an object of NodeFN which holds a string.
}

public void add(String n) {
    NodeFN nn = new NodeFN(n); // nn is now an object of NodeFN class which holds a string.
    if(head == null) { // If head is null.
        head = nn; // Make head equal to the first node.
    }

    if(nn.getData().compareTo(head.getData()) < 0) {
        nn.setNext(head); // Puts nn in the beginning in the list.
        head = nn; // Makes sure nn is in the beginning of the list.
    }
}

public void delete() {
    NodeFN nn = new NodeFN(n);

    while(head.getNext() != null) {
        head = head.getNext(); 
    }   
    head = nn;
}

public void peek() {
    NodeFN nn = new NodeFN(n);

    while(nn.getData().compareTo(head.getData()) > 0) {
        System.out.println(head.getData() + " ");
        head = head.getNext();
    }
}

public void print() {
    if(head == null) { // If head is empty.
        System.out.println(); // Print nothing.
    }

    while(head != null) { // While head is filled with data
        // Print the data so long as the add() method has a valid string parameter.
        System.out.println(head.getData() + " "); 
        head = head.getNext(); // head will get to the next node and print.
    }
}

public static void main(String[] args) {
    Queue q = new Queue("test1");
    q.add("test2");
    q.add("test3");
    q.add("test4");
    q.peek();
   } 
}

【问题讨论】:

  • 为什么你的delete 不接受任何参数?不应该取String,然后删除以该字符串为数据的节点吗?
  • 没有String就没有办法做到这一点?我很确定有。

标签: java oop nodes peek


【解决方案1】:

我相信 peek 应该只返回当前队列头的副本,并且不对当前队列进行任何更改。

public void peek() {
       NodeFN nn = new NodeFN(n);

       while(nn.getData().compareTo(head.getData()) > 0) {
            System.out.println(head.getData() + " ");
            head = head.getNext();
       }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2018-07-21
    • 1970-01-01
    • 2013-10-26
    相关资源
    最近更新 更多