双指针经典例题

我们都知道C语言中的指针使用的好的话 对使用C语言的程序员来说如虎添翼
指针的使用多种多样!
下面我们来看一道关于双指针的使用!
可以体会一下指针的灵活妙用!
给定一个链表,返回链表开始入环的第一个节点。 如果链表无环,则返回 null。

为了表示给定链表中的环,我们使用整数 pos 来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos 是 -1,则在该链表中没有环。

说明:不允许修改给定的链表。

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/linked-list-cycle-ii

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
 typedef struct ListNode ListNode;
struct ListNode *detectCycle(struct ListNode *head) 
{
    //首先判断是否有环并找到相遇点 利用快慢指针
    if(head==NULL||head->next==NULL)
        return NULL;
        
    ListNode* fast=head->next->next;
    ListNode* slow=head->next;
    while(1)
    {
        if(fast==NULL||fast->next==NULL)
            return NULL;

        if(fast==slow)
            break;

        fast=fast->next->next;
        slow=slow->next;
    }
    //已经得到相遇节点
    while(1)
    {
        if(head==slow)
        {
            return head;
        }
        
        slow=slow->next;
        head=head->next;
    }
    
    
}

猜你喜欢

转载自blog.csdn.net/ifwecande/article/details/103605469
今日推荐