2016-11-07 30 views
0

我已经想出了add()print()方法。现在我想让我的delete()peek()方法起作用。我无法找出我的代码多次尝试多次的问题。使用Java中的方法删除节点

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;} 
} 

Queue类:

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(); 
    } 
} 
+0

为什么你的'delete'不带任何参数?是否不需要'String',然后删除一个包含该字符串作为数据的节点? – DUman

+0

没有办法做到这一点,而不需要'String'?我很确定有。 – g24

回答

0

我相信偷看应仅返回副本当前队列头,没有做对当前队列中的任何改变。

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

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