【发布时间】: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