0

I'm trying to create a constructor for a Deck class which has only one field: a pointer to a node class object. A node has two fields, a card object and a pointer to another node (linked list).

I'm trying to build a deck of cards using this construct but when I print it, it only displays one card, leading me to believe that the constructor doesn't work properly.

My printing method works fine, I've tested it with other examples. I'm intentionally starting the deck with the same card twice as I was going to remove it later.

Deck::Deck(){
    node* phead;
    phead = new node(Card("A","Heart"));
    node* curr;
    node* next;
    curr = phead->next;

    string suits[4] {"Heart", "Spade", "Club", "Diamond"};
    string values[13] {"A","2","3","4","5","6","7","8","9","10","J","Q","K"};

    for(int i = 0; i < 4; i++){
        for(int j = 0; j < 13; j++){
            curr = new node();
            curr->card = Card(values[j], suits[i]);
            next = curr->next;
            curr = next;
        }
    }
    curr=NULL;
    deck = phead;
}
2
  • Hint: You're not linking between your nodes properly. Commented Feb 6, 2016 at 23:46
  • Should not be 'curr=phead' at the end of your variable declarations Commented Feb 6, 2016 at 23:53

1 Answer 1

1

Instead of setting curr = phead->next, try phead->next = curr

Your code appears to be setting the value of curr to the value of phead->next, which is never being changed in this code.

Setting phead->next to curr will make it so that the phead list contains the node which is being created in the curr value, adding curr to your linked list.

I hope this helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the help! Really appreciate it, linked list are a little tricky

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.