一.Linked List Cycle
Total Accepted: 85115 Total Submissions: 232388 Difficulty: Medium
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */ class Solution { public: bool hasCycle(ListNode *head) { if(head==NULL || head->next==NULL){ return false; } ListNode *first =head; ListNode *second = head; while(first && second) { first = first->next; second = second->next; if(second){ second = second->next; } if(first==second){ return true; } } return false; } };
Next challenges: (M) Linked List Cycle II
二.Linked List Cycle II
Total Accepted: 61662 Total Submissions: 196038 Difficulty: Medium
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?
(M) Linked List Cycle (H) Find the Duplicate Number
时间: 2024-11-09 03:41:07