Given a linked list, return the node where the cycle begins. If there is no cycle, return
There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally,
Notice that you should not modify the linked list.
null
.There is a cycle in a linked list if there is some node in the list that can be reached again by continuously following the next pointer. Internally,
pos
is used to denote the index of the node that tail's next
pointer is connected to. Note that pos
is not passed as a parameter.Notice that you should not modify the linked list.
Example:
Input: 3->2->0->4->back to 2
Output: Cycle
Approach
Java
public class LinkedListCycleII {public static void main(String[] args) {ListNode head = new ListNode(3);head.next = new ListNode(2);ListNode temp = head.next;head.next.next = new ListNode(0);head.next.next.next = new ListNode(4);head.next.next.next.next = temp;ListNode cycle = detectCycle(head);if (cycle == null)System.out.println("No Cycle");elseSystem.out.println("Cycle");}static public ListNode detectCycle(ListNode head) {ListNode cNode = hasCycle(head);if (cNode == null) {return null;} else {return firstNode(head, cNode);}}// find the first cycle nodeprivate static ListNode firstNode(ListNode l, ListNode cNode) {while (cNode != null) {if (l == cNode)return l;cNode = cNode.next;l = l.next;}return null;}// function to check if linked// list contains cycle or notprivate static ListNode hasCycle(ListNode head) {ListNode slow = head;ListNode fast = head;// move slow pointer one time and// fast pointer 2 timeswhile (fast != null) {fast = fast.next;if (fast != null) {slow = slow.next;fast = fast.next;// if both slow and fast are// at same place then return true// means cycle is presentif (slow == fast)return slow;}}// no cyclereturn null;}}
C++
#include <bits/stdc++.h>using namespace std;//Struture of nodestruct Node{int data;Node *next;Node(int data){this->data = data;this->next = NULL;}};//function to detect the cycle in linked listNode *detectCycle(Node *head){if (head == NULL || head->next == NULL)return NULL;Node *slow = head, *fast = head;slow = slow->next;fast = fast->next->next;while (fast && fast->next){if (slow == fast)break;slow = slow->next;fast = fast->next->next;}if (slow != fast)return NULL;slow = head;while (slow != fast){slow = slow->next;fast = fast->next;}return slow;}int main(){Node *head = new Node(3);head->next = new Node(2);Node *temp = head->next;head->next->next = new Node(0);head->next->next->next = new Node(4);head->next->next->next->next = temp;Node *cycle = detectCycle(head);if (cycle == NULL)cout << "No Cycle";elsecout << "Cycle";return 0;}
No comments:
Post a Comment