Home > Mobile >  checking every node in a linked list for a condition in c
checking every node in a linked list for a condition in c

Time:12-01

so I have a linked list that's meant to represent a hand of five playing cards. I'm trying to write a function to check if the cards are a royal flush. The first thing I do is check if the suit of the all the cards is the same. The next bit is where I'm having trouble. My idea is that I'd check if any of the cards are a king (13). If there is one, then it would go through the list again checking for a queen, jack, ace, and 10, and if at any point a card isn't found, it returns 0. If all the cards are there and they have the same suit, the function returns 1. This is what I've got so far:

int royalFlush(card* pHand) {
    card* temp = pHand;

    if (!suitCheck(temp)) {
        return 0;
    }

    else {
        while (temp != NULL) {
            //check if the card has the right face here
            temp = temp->next;
        }
    }
} 

int suitCheck(card* pHand) {
    card* tmp;
    tmp = pHand;
    while (tmp != NULL) {
        if (tmp->suit != tmp->next->suit) {
            return(0);
        }
        tmp = tmp->next;
    }
    return(1);
}

I'm having trouble figuring out how to move from one card to the next and check if the face of each card has the correct value. I'm also unsure if this: tmp->next->suit is something that the compiler can read properly.

CodePudding user response:

Assuming the cards are sorted by suit and by descending value,

  1. If the hand is empty,
    1. Return false.
  2. Get the suit of the first card.
  3. Create array [ Ace, King, Queen, Jack, Ten ].
  4. Set i to the index of the first element of the array.
  5. Set the current card to the first card.
  6. While the current card isn't empty and i is within the bounds of the array,
    1. If the suit of the current card doesn't match the suit of the first card,
      1. Return false.
    2. If the rank of the current card doesn't match the rank corresponding to index i,
      1. Return false.
    3. Increment i.
    4. Make the current card the following card.
  7. Return True.

Note that a linked list if a very weird structure to be using for a card game hand.

CodePudding user response:

Welcome to SO! Hope you enjoy your time here.

If you're able to modify the function signature a bit, you could do something like this:

int suitCheck(card *pHand, suit expected_suite)
{
  if(pHand == NULL) {
    return 0; /* You can remove this if you're absolutely sure the initial next of the original pHand is not NULL */
  }
  while(pHand) {
    if(pHand->suite != expected_suite) {
      return 0;
    }
  }
  return 1;
}

Then you'd call it from the main code like so:

if(suitCheck(temp->next, temp->suite)) {

I'll leave it to you to imagine how to accomplish the same feat without modifying the function signature.

  • Related