【问题标题】:Insert function for singly linked list using two structs C programming使用两个结构 C 编程的单链表插入函数
【发布时间】:2017-10-21 00:56:08
【问题描述】:

我不确定我在单链表中插入节点的实现是否正确。我知道如何使用节点和数据插入它,但为此,必须使用两个结构进行插入。所以我有两个结构,一个具有花色和 cardValue 值的卡片结构和一个具有下一个指针和卡片结构的节点结构。我想将卡片数据插入到有序列表中的节点中。我还创建了自己的函数来比较这些值。这是我所拥有的:

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;
}

【问题讨论】:

  • 嗨泡泡。你有什么问题?
  • 您的 insertNode 实际上并没有插入任何内容,也没有返回任何内容

标签: c


【解决方案1】:

将结构插入到链表中与插入任何其他类型的数据相同:

  1. 传递指向列表头部的指针
  2. 前往列表中的所需位置
  3. 将上一个节点指向新元素,将新元素指向该位置的上一个节点

考虑到这一点,您的 insertNode 函数应该有所改变。首先,您应该传入一个已经创建的 Node*,而不是当前传入的 Card*。您正在寻求将另一个节点添加到您的清单,而不仅仅是一张卡片。此外,您通常希望传入链表的 Head 节点。考虑到这一点,这里有一些东西可以帮助您!

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;
   }
}

【讨论】:

  • 这个函数没有提供任何方法来添加一个节点到一个空列表中。
  • @aschepler 你是完全正确的。在这里,我假设由于他的函数名称,他已经有了某种形式的链表,但如果他需要进一步的帮助,我很乐意改变我的链表
猜你喜欢
  • 2012-11-21
  • 2014-11-29
  • 2017-10-23
  • 1970-01-01
  • 1970-01-01
  • 2015-11-01
  • 1970-01-01
  • 2021-01-09
  • 1970-01-01
相关资源
最近更新 更多