2016-11-07 10 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;} 
} 

キュークラス:

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

私がpeekは、現在のキューヘッドコピーを返す必要がありますし、現在のキュー上の任意の変更を行いませんと信じています。

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

     while(nn.getData().compareTo(head.getData()) > 0) { 
      System.out.println(head.getData() + " "); 
      head = head.getNext(); 
     } 
} 
関連する問題