gpt4 book ai didi

c - 如何从链接列表中删除循环

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:59:54 26 4
gpt4 key购买 nike

例如,如果链接列表是这样的:

1->2->3->4->5->6->7->8->9->4

我们可以使用 Floyd 循环算法找到循环,但是在这种情况下如何删除循环?

最佳答案

1) Detect Loop using Floyd’s Cycle detection algo and get the pointer to a loop 
node.
2) Count the number of nodes in loop. Let the count be k.
3) Fix one pointer to the head and another to kth node from head.
4) Move both pointers at the same pace, they will meet at loop starting node.
5) Get pointer to the last node of loop and make next of it as NULL.

例如你的情况:1->2->3->4->5->6->7->8->9->4

1) Loop verified by Floyd's cycle detection algo.
2) count of nodes in loop = 6
3) head->1, p->7 (6th node from head)
4) Loop while head!=p head=head->next and p=p->next. Both will meet at node 4
5) p=p->next Loop while(p->next!=head) p=p->next;
Put p->next=NULL after termination of above loop. Your new list will be 1->2->3->4->5->6->7->8->9->NULL

关于c - 如何从链接列表中删除循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24585129/

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