0

リンクされたリストの末尾に次の番号を追加するプライベート再帰挿入関数を呼び出す挿入関数が必要です。どのパラメーターを使用する必要があり、再帰挿入関数に何を含める必要があるかについて問題があります。再帰挿入関数には、再帰的にステップスルーするノード ポインターが必要だと考えています。

class LinkedList{
    private:
        struct Node{
            int data; //stores data in nodes
            Node* next;
            ~Node(){delete next;}
        };
    public:
    LinkedList(){ first = NULL;}
    ~LinkedList(){delete first;}

    void print() const {
      print( first );
    }
    void insert(const int d){ //here is where the first insert method is
    insert(first, d);
    }
private:
    Node* first;

これが私が立ち往生している機能です...

void insert(Node* p, const int d){ //this is the private recursive one
        Node* temp = new Node;
        temp->data=d;
        if(p->next == NULL) p->next = temp;
        else insert(p->next, d);
        }

};

int main() {
int a[] = { 1, 2, 3, 4, 5, 6};
LinkedList list;
  for(int i=0; i<6; i++)
    list.insert( a[i] );
}

パラメータを変更して挿入関数をオーバーロードする方法を知りたいです。また、再帰関数を正しくステップ実行しているかどうかも知りたいです。

4

2 に答える 2

2

再帰関数を呼び出す関数は次のようになります。

void insert(const int d){
        insert(first, d);
    }

再帰関数は次のようになります

void insert(Node*& p, const int d){
    Node* temp = new Node;
    temp->data=d;
    if(p == NULL) p = temp;
    else insert(p->next, d);
}
于 2013-04-07T00:22:19.340 に答える
0

新しいノードを割り当てる前に、リストの最後に到達する必要があります。以下のこのバージョンは、これまでに書いたものと最も互換性があります。

void insert(Node*& p, const int d) {
    if (p == NULL) { // reached the end, so allocate new node and set value
        p = new Node;
        p->data = d;
        p->next = NULL;
    }
    else
        insert(p->next, d);
}
于 2013-04-06T07:16:47.857 に答える