2016-03-28 12 views
0

ノードをリンクリストに追加する方法を作成しようとしていますが、これまでのところ失敗しています。ここに私の体に私のコードだvarsは:リンクリストのadd()メソッド

private Object data; 
private int size = 0; 
private Node head = null; 
private Node tail = null; 

    public void add(Object item){ 
    Node temp = head; 
    if (head != null) { 
     // THIS IS THE PROBLEM SITE 

     while(temp.getNext()!=null){ 
      temp=temp.getNext(); 
     } 
     //set next value equal to item 
     Node ab = (Node) item; // It says this is an invalid cast. How do I get around this?? 
     ab.setNext(ab); 

    } 
    else{ 
     head = new Node(item); 
    } 
    size++; 
} 

はまたここに参照のための私のNodeクラスです:お時間を

public class Node { 

// Member variables. 
private Object data; // May be any type you'd like. 
private Node next; 

public Node(Object obj) { 
    this.data = obj; // Record my data! 
    this.next = null; // Set next neighbour to be null. 
} 
// Sets the next neighbouring node equal to nextNode 
public void setNext(Node nextNode){ 
    this.next=nextNode; 
} 
// Sets the item equal to the parameter specified. 
public void setItem(Object newItem){ 
    this.data = newItem; 
} 
// Returns a reference to the next node. 
public Node getNext(){ 
    return this.next; 
} 
// Returns this node ís item. 
public Object getItem() { 
    return this.data; 
} 

ありがとう!

+0

「失敗」とは何かを説明できますか?エラーが発生していますか? – pczeus

+0

私はこれがhttp://stackoverflow.com/questions/5797548/c-linked-list-inserting-node-at-the-endの複製であると信じています –

+0

将来的には、あなたが得る例外を追加するべきです他の問題の分離/理解が容易になります。 –

答えて

7

あなたがノードとしてごitemをキャストしたくない、あなたはこの代わる新しいノードを作成し、item

することでdataを設定したい:何かに

Node ab = (Node) item; // It says this is an invalid cast. How do I get around this?? 
ab.setNext(ab); 

Node newNode = new Node(); 
newNode.setData(item); 
temp.setNext(newNode); 
関連する問題