gpt4 book ai didi

c - C中的合并链表

转载 作者:太空宇宙 更新时间:2023-11-04 05:08:29 24 4
gpt4 key购买 nike

我在采访中被问到这个问题:有两个链表的两个表头。c中有一个合并链表,其中第二个链表在某个时候合并到第一个链表中。我们如何确定合并点,找到该点的复杂性如何?

有人可以帮忙吗?

最佳答案

O(n)

search = list1->header;
if (mixed->header == list1->header) search = list2->header;

while (mixed->next != search) mixed = mixed->next;

编辑:变量的新名称和一些注释

/* search is what we want to find. Here it's the head of `list2` */
search = list2->header;
/* unless the merging put `list2` first; then we want to search for `list1` */
if (mixed->header == list2->header) search = list1->header;

/* assume (wrongly) that the header for the mixed list is the merge point */
mergepoint = mixed->head;

/* traverse the mixed list until we find the pointer we're searching */
while (mergepoint->next != search) mergepoint = mergepoint->next;
/* mergepoint now points to the merge point */

关于c - C中的合并链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1887111/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com