Given a linked list, return the node where the cycle begins. If there is no cycle, return null
Example 1:
Input: head = [3,2,0,-4], pos = 1
Output: 2
Explanation: There is a cycle in the linked list, where tail connects to the second node.
Approach
Java
public class LinkedListCycleFirstNode {public static void main(String[] args) {ListNode l = new ListNode(3);l.next = new ListNode(2);ListNode tmp = l.next;l.next.next = new ListNode(0);l.next.next.next = new ListNode(-4);l.next.next.next.next = tmp;ListNode cNode = hasCycle(l);if (cNode == null) {System.out.println("No cycle");} else {ListNode cycleNode = firstNode(l, cNode);System.out.println(cycleNode.val);}}// 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;}}class ListNode implements Comparable<ListNode> {int val;ListNode next;ListNode() {}ListNode(int val) {this.val = val;}ListNode(int val, ListNode next) {this.val = val;this.next = next;}@Overridepublic int compareTo(ListNode o) {if (this.val == o.val)return 0;else if (this.val > o.val)return 1;elsereturn -1;}}
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;}};// find the first cycle nodeNode *firstNode(Node *l, Node *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 notNode* hasCycle(Node *head){Node *slow = head;Node *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;}int main(){Node *l = new Node(3);l->next = new Node(2);Node *tmp = l->next;l->next->next = new Node(0);l->next->next->next = new Node(-4);l->next->next->next->next = tmp;Node *cNode = hasCycle(l);if (cNode ==NULL) {cout<<"No cycle";}else {Node *cycleNode = firstNode(l, cNode);cout<<cycleNode->data;}return 0;}
No comments:
Post a Comment