Given head
, the head of a linked list, determine if the linked list has a cycle in it.
Example:
Input: 3->2->0->(-4)->points back to 2
Output: Cycle
Approach
Java
public class LinkedListCycle {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;System.out.println(hasCycle(l));}// function to check if linked// list contains cycle or notprivate static boolean 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 true;}}// no cyclereturn false;}}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;}};//function to check if linked// list contains cycle or notbool hasCycle(Node *head){Node *slow=head,*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 true;}}//no cyclereturn false;}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;if(hasCycle(head))cout<<"Cycle\n";elsecout<<"No Cycle\n";return 0;}
No comments:
Post a Comment