我不确定我在单链表中插入节点的实现是否正确。我知道如何使用节点和数据插入它,但为此,必须使用两个结构进行插入。所以我有两个结构,一个具有suit和cardValue值的card结构和一个具有下一个指针和card结构的节点结构。我想将卡数据插入到有序列表中的节点中。我还创建了自己的函数来比较值。这就是我所拥有的:
typedef struct _Card
{
char cardValues[2];
char suits;
} Card;
typedef struct _Node
{
struct Card *card;
struct Node *next;
} ListNode;
ListNode *insertNode(ListNode *prev, Card *data)
{
ListNode *current = prev;
while((current->next != NULL) && (compareStruct(prev, data) < 0))
{
prev = prev->next;
}
}
int compareStruct(ListNode *node, Card *card)
{
int retVal = 0;
if(strcmp(node->next->card->cardValues, card->cardValues) < 0)
retVal = 0;
else
retVal = 1;
return retVal;
}
答案 0 :(得分:2)
将结构插入链接列表与插入任何其他类型的数据相同:
考虑到这一点,关于insertNode函数应该改变一些事情。首先 - 您应该传入已经创建的节点* ,而不是您当前传入的卡* 。您正在寻找将另一个节点添加到您的列表,而不仅仅是一张卡片。此外,您通常希望传入链表的头节点。考虑到这一点,这里有一些东西可以帮助你!
void insertNode(ListNode* node, ListNode* toInsert) {
while(node->next != null && **Your comparison function here**) {
node = node->next;
}
//Here check if you added at the end, or in the middle
if(node->next == null) {
//This is the end of the list - simply add
node->next = toInsert;
toInsert->next = null;
}
else {
//If you're here, you added in the middle.
ListNode* temp = node->next;
node->next = toInsert;
toInsert->next = temp;
}
}