这两个题是相关联的,主要做法为哈希和快慢指针,当然像博主我,不看解析只会O(n^2)的暴力遍历,太惨了,不过,快慢指针还是很好理解的,是一个追及的问题,
目录
题目:
编辑 快慢指针解法原理:
代码LeetCode:141:
每日表情包:
题目:
快慢指针解法原理:
代码LeetCode:141:
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
bool hasCycle(struct ListNode *head) {struct ListNode* pfast = head, * pslow = head;while(pfast && pfast->next){pfast = pfast->next->next;pslow = pslow->next;if(pfast == pslow){return true;}}return false;
}
代码LeetCode:142:
/*** Definition for singly-linked list.* struct ListNode {* int val;* struct ListNode *next;* };*/
struct ListNode *detectCycle(struct ListNode *head) {struct ListNode* pfast = head, * pslow = head;while(pfast && pfast->next){pfast = pfast->next->next;pslow = pslow->next;if(pfast == pslow){while(pfast != head){pfast = pfast->next;head = head->next;}return head;}}return NULL;
}
每日表情包:
点点赞吧 ~ 可怜可怜孩子。