【问题标题】:Add only new data to linked list in C仅将新数据添加到 C 中的链表
【发布时间】:2016-12-04 04:02:54
【问题描述】:
if (!head->next) {
    head->next = newNode;   /* if only dummy node, add node to end of list */
} else {
    /* iterates through linked list until a node is found that is greater than the new node */
    while (head->next && strcmpa((head->next)->data, newNode->data) < 0) 
        head = head->next;
    if (!head->next) {
        head->next = newNode;   /* adds new node to end list if no nodes are greater in value */    
    } else {
        newNode->next = head->next;     /* points new node to the next node */  
        head->next = newNode;   /* points current node to new node */
    }
}

如何编辑此代码以使其拒绝任何数据字段等于列表中已存在的节点的新节点?

【问题讨论】:

  • 您需要遍历链表中当前存在的所有节点,并始终检查新节点的值是否等于当前节点的值。如果是则停止迭代。如果列表中没有节点与新节点具有相同的值,则循环将在列表中的最后一个节点处结束,其中 'currentNode->next' 等于 NULL。此时,您需要通过使列表中的最后一个节点指向新节点来添加新节点。然而,如果你想让你的列表保持排序,你可以运行你提供的代码来插入排序。

标签: c linked-list nodes


【解决方案1】:

把最后一个else {改成

else if(strcmp(head->next->data, newNode->data)) {

【讨论】:

  • 你这个男人。谢谢。看了这么久的代码,我什至不知道它是什么意思了。
  • @namarino 很高兴为您提供帮助:D
猜你喜欢
  • 2015-02-06
  • 1970-01-01
  • 2016-12-28
  • 2014-11-05
  • 2015-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多