我正在开发一个最终项目,需要为纸牌游戏实现一个链表。庄家的手牌和玩家的手牌都应该是链表以及一副牌。
我遇到的问题是当我尝试创建一个将值(牌组列表末尾的牌)添加到其中的函数时。传递列表本身及其尾部不会更新它们的值。我可以创建该函数,使其返回头指针,但这样我将无法记下它的尾部。
我真的很抱歉,因为这对我来说是新事物,而且我在这门类(class)之前从未编程过。如果我的函数中的某些逻辑看起来不必要地难以阅读,或者直接没有意义,请原谅我。
我不断地尝试让这项工作成功,但我有一种感觉,我正在做一些根本错误的事情
typedef struct card_s {
char suit[20];
int face;
struct card_s *next, *previous;
} card;
card* createHands(card* head, card *cards) {
card *tail = NULL, *temp = NULL, *temp1;
// Go to end of deck
while (cards->next != NULL) {
cards = cards->next;
}
temp = (card *)malloc(sizeof(card));
strcpy(temp->suit, cards->suit);
temp->face = cards->face;
if (head == NULL) { // If the list for the hand doesn't exist, create head
head = temp;
}
else {
tail->next = temp;
}
tail = temp;
tail->next = NULL;
temp1 = cards->previous;
free(cards); // to delete the node added from the deck
cards = temp1;
cards->next = NULL;
while (cards->previous != NULL) {
cards = cards->previous;
}
return head;
}
显然,这只会将我给它的任何值添加到之前的值之上。它绝不是一个连接列表。
我将不胜感激任何帮助!
最佳答案
对函数的用途进行大量假设
typedef struct card_s {
char suit[20];
int face;
struct card_s *next, *previous;
} card;
您想要添加一张手牌
card* AddCard(card* hand, card* draw) {
// check input
if(draw == NULL ) {return NULL;}
// create a copy of the card
card* newCard=malloc(sizeof(card));
if(newCard == NULL) {return hand;} // check malloc result
memcpy(newCard, draw, sizeof(card));
newCard->next=NULL;
newCard->previous=NULL;
if(hand==NULL) {return newCard;} // if the hand was null just return the card
// find where to append the card
card* tail=hand;
while(tail->next != NULL) {tail = tail->next;}
// append the card to the end of the hand
tail->next = newCard;
newCard->previous = tail;
return hand;
}
关于c - 通过引用传递链表的结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55791895/