LeetCode:142. Linked List Cycle II

题目链接:

Linked List Cycle II


题目描述:

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.
Follow up:
Can you solve it without using extra space?


题目解释:

题目的要求比较简单,给定一个链表,如果这个链表是循环的,找出这个链表循环开始的地方,如果这个链表并没有循环,则返回NULL。
当然题目还要求空间复杂度为O(1).


解题方案:

  1. 利用快慢指针,判断该链表是否为循环链表,并找出循环中的一个节点。
  2. 如果为循环指针,从链表头部开始判断当前节点是否在循环区域。
  3. 判断当前节点是否在循环区域的方式为:利用步骤1找到的节点fast,迭代求fast节点的下一节点,如果该节点在循环内,那么该节点肯定会与fast相遇,若不在循环中,fast节点会与步骤1中的慢指针相遇。

AC代码:

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     struct ListNode *next;
 * };
 */
struct ListNode *detectCycle(struct ListNode *head) {

  if(head == NULL) return NULL;

  struct ListNode *fast = head;
  struct ListNode *slow = fast;
  bool isCycle = false;

  while(true){
    fast = fast->next;
    if(!fast) break;
    fast = fast->next;
    if(!fast) break;

    slow = slow->next;

    if(fast == slow){
      isCycle = true;
      break;
    }
  }
  printf("%d %d\n", slow->val, isCycle);

  if(isCycle){
    struct ListNode *f = head;

    while(f){
      if(f == fast) return f;

      while(true){
        fast = fast->next;
        if(f == fast) return f;

        if(slow == fast) break;
      }
      f = f->next;
    }
  }
  else
    return NULL;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值