首页 > 解决方案 > 如果链接列表中存在循环,则删除循环

问题描述

我正在尝试编写可以从链表中删除循环的代码,如果列表中有的话。

Input:
N = 3 //total number of nodes in the list
value[] = {1,3,4}
C = 2 //position of the last connected node, if it is zero it is not connected
Output: 1

void removeLoopLlinkedList(Node* head)
{
    if(!head) return;
    
    Node* first= head->next;
    Node* last= head;  
    
    while( first!= last)
    {
        if( !first|| !last->next ) return;
        first=first->next->next;
        last=last->next;
    }
    
    int size = 1;
    first = first->next;
    while( first== last)
    {
        size++;
        first= first->next;
    }
    
    
    first= head;
    for(int i=0; i<size-1; i++)
        first= first->next;
    
    while( last->next != last )
    {
        first= first->next;
        last= last->next;
    }
}

我找不到我的错误,也没有得到想要的输出。我怎么解决这个问题?

先感谢您!

标签: clinked-list

解决方案


推荐阅读