使用Java中的方法删除节点

时间:2016-11-07 00:12:34

标签: java oop nodes peek

我已经找到了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();
   } 
}

1 个答案:

答案 0 :(得分:0)

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

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

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