【发布时间】:2019-09-11 11:57:52
【问题描述】:
我正在完成一个需要为纸牌游戏实现链接列表的最终项目。庄家手和闲家手都应该是链表以及一副牌。
我遇到的问题是,当我尝试创建一个将值(来自套牌列表末尾的卡片)添加到它的函数时。将列表传递给它自己及其尾部不会更新它们的值。我可以使函数返回头指针,但是我将无法记下它的尾巴。
我真的很抱歉,因为这对我来说是新事物,而且我在这门课程之前从未编程过。如果我的函数中的某些逻辑看起来不必要地难以阅读,或者直接没有意义,请原谅我。
我已经无休止地尝试让这项工作发挥作用,但我觉得我做的事情根本上是错误的
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;
}
显然,这只会将我给它的任何值添加到以前的值之上。这绝不是一个连接列表。
我将不胜感激!
【问题讨论】:
-
free 旧节点并 malloc 一个新节点没有任何意义 - 只需将 that 节点放入正确的列表中并完成它!
-
我明白你的意思,我会尽快修复这个功能。
-
N,你应该努力在你的问题中产生一个minimal reproducible example。例如,请注意最后一个 while 循环实际上没有任何效果。
-
您永远不会为分配的节点设置
previous。所有这一切都源于您的函数是如此复杂,以至于每个人都很难弄清楚其中发生了什么。 -
if (head == NULL)- 什么时候 not 在初次进入此函数时为真?我的意思是,当您将非空head传递给这个东西时?这个函数到底应该做什么?如果你不能走你的代码和explain it to your rubber duck,你将很难向我们解释它。
标签: c pointers linked-list