leetcode刷题日记—— Linked List Cycle II
来源:互联网 发布:seo是什么意思 编辑:程序博客网 时间:2024/06/05 21:13
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:
Note: Do not modify the linked list.
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: ListNode *detectCycle(ListNode *head) { if(head==NULL) return NULL; if(head->next==NULL) return NULL; ListNode *p=head,*q=head,*m=NULL; while(p&&q->next){ p=p->next; q=q->next->next; if(q==NULL) return NULL; if(p==q) { q= head; while(q!=p) { p= p->next; q= q->next; } m= p; break; } } return m; }};
0 0
- leetcode刷题日记—— Linked List Cycle II
- leetcode刷题日记——Linked List Cycle
- LeetCode——Linked List Cycle II
- LeetCode——Linked List Cycle II
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- LeetCode——141. Linked List Cycle && 142. Linked List Cycle II
- leetCode刷题归纳-linked list(141. Linked List Cycle&& Add to List 142. Linked List Cycle II)
- LeetCode刷题笔录Linked List Cycle II
- leetcode 刷题之路 59 Linked List Cycle II
- leetcode——142——Linked List Cycle II
- leetcode 142 —— Linked List Cycle II
- LeetCode题解——Linked List Cycle II
- Leetcode——142. Linked List Cycle II
- LeetCode — Linked List Cycle II 解题报告
- LeetCode 之 Linked List Cycle I II — C++ 实现
- 【LeetCode】 Linked List Cycle II
- DescriptionResourcePathLocationType AppliToolingPart cannot be resolved to a typeAppliToolingPa
- 【翻译自mos文章】跟踪UNIX系统调用的方法
- 【虫师--系列】LR有的JMeter也有之一“参数化”
- 【虫师--系列】LR有的JMeter也有之二“检查点”
- App Store最新审核指南(2015年3月更新版)
- leetcode刷题日记—— Linked List Cycle II
- Qwt中的鼠标操作之缩放、平移
- 解决视网膜屏上看网页图片模糊的问题?
- 【虫师--系列】LR有的JMeter也有之三“集合点”
- 任性走通在线教育之路——如鹏创业一年总结
- .Net 环境下,有母版网页中的控件遍历
- iOS UIWebView
- 【虫师--系列】一种简单的数据库性能测试方法
- android gradle 多渠道打包分发