LeetCode:142. Linked List Cycle II

来源:互联网 发布:2016fc2破解版域名设置 编辑:程序博客网 时间:2024/05/03 12:57

题目链接:

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;}
0 0
原创粉丝点击