我有2个链表,我想将两个元素中的元素复制到newSet中,这样我就可以删除newset中的deplicate值并显示它。到目前为止,一切似乎都出错了,它没有复制集。
struct Node *Union(struct Node *Link1, struct Node *Link2)
{
struct Node * set1 = Link1;
struct Node * set2 = Link2;
//Creat a new set
struct Node * newSet = (struct Node *) malloc(sizeof(struct Node));
while(set1 != NULL && set2 != NULL)
{
//copy sets to newSet
newSet->data = set1->data;
newSet->data = set2->data;
newSet->next = Union(set1->next, set2->next);
}
return (newSet);
}
任何帮助适用
答案 0 :(得分:1)
您的主要问题是您为新值分配了一个节点,然后用两个列表和两个指针的头部覆盖它。这意味着你将失去每一个节点。
此外,连接两个列表确实非常适合递归,因为搜索空间不会减少那么快(理想的递归候选者,如二进制印章或多路树遍历,每次递归调用都会丢弃大量的搜索空间)。您可以使用类似的方式迭代地执行此操作(假设按升序排序,并使用伪代码,因为它是作业):
def union (link1, link2):
set1 = link1, set2 = link2
headnode = NULL, tailnode = NULL
# Continue until both lists empty.
while set1 is not NULL and set2 is not NULL:
# Create new node and set next pointer to NULL.
newnode = alloc_node()
newnode->next = NULL
# Select which set will provide the next node.
if set1 is NULL:
newnode->data = set2->data, set2 = set2->next
else if set2 is NULL:
newnode->data = set1->data, set1 = set1->next
else if set2->data is less than set1->data:
newnode->data = set2->data, set2 = set2->next
else:
newnode->data = set1->data, set1 = set1->next
# Add to end of (possibly empty) list.
if headnode is NULL:
headnode = newnode, tailnode = newnode
else:
tailnode->next = newnode, tailnode = newnode
return headnode
它基本上通过添加到目标列表的每个节点执行一次迭代来工作,直到两个源列表都为空。如果其中一个源列表为空,则从另一个列表中选择下一个节点。
否则,它从列表中选择当前指针具有最低值的下一个节点。