常见面试题-环形链表

环形链表-找环点

leetcode: 141-环形链表
判断是否有环

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
bool hasCycle(struct ListNode *head) {
    struct ListNode* start = head;
	struct ListNode* end = head;

	while (end)
	{
		start = start->next;
        if (end == NULL || (end = end->next) == NULL)
		{
			return false;
		}
		end = end->next;
		if (start == end)
		{
			return true;
		}
	}
    return false;
}

leetcode: 142-环形链表2
找第一个环点
方法一 :常用二指针找环的方法,两倍速,则相遇点到环入口的距离和链表头结点到链表环入口的距离相等。

struct ListNode * hasCycle(struct ListNode *head) {
    if(head==NULL)
        return false;
    struct ListNode *slow=head;
    struct ListNode *fast=head;
    while(fast!=NULL&&fast->next!=NULL){
        slow=slow->next;
        fast=fast->next->next;
        if(fast==slow)
            return fast;
    }
    return NULL;   
}
struct ListNode *detectCycle(struct ListNode *head){
    struct ListNode * i=hasCycle(head);
    if (i)
    {
       struct  ListNode* q = head;
        while (i != q) {
            i = i->next;
            q = q->next;
        }
        return q;
    }
    else return NULL;
    
}

方法二:


/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
#define sl  struct ListNode*
bool iscycle(struct ListNode* head)
{
	sl step1 = head;
	sl step2 = head;

	while (step1)
	{
		step1 = step1->next;
		if(step2 == NULL || (step2 = step2->next) == NULL )
		{
			return false;
		}
		step2 = step2->next;
		if (step1 == step2)
		{
			return true;
		}
	}
	return false;
}
struct ListNode *detectCycle(struct ListNode *head) {
	if (head == NULL)
	{
		return NULL;
	}
	sl tmp = head;
	sl pre = tmp;
	bool isc = false;
	isc = iscycle(head);
	if (isc == false)
	{
		return NULL;
	}
	else
	{
		isc = false;
	}
	while (tmp)
	{
		pre = tmp;
		tmp = tmp->next;
		pre->next = NULL;
		isc = iscycle(tmp);
		pre->next = tmp;
		if (isc != true)
		{
			return pre;
		}
	}
	return NULL;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值