[LeetCode 第11题] -- Linked List Cycle II
来源:互联网 发布:病态矩阵 编辑:程序博客网 时间:2024/06/06 03:23
题目链接: Linked List Cycle II
题目意思: 给定一个链表,如果链表有环求出环的起点,否则返回NULL
解题思路:
1. 判断链表是否有环: 两个指针,一个一次走一步,一个一次走两步,如果指针相遇说明有环,否则无环。
2. 如果有环的情况下,我们可以画个图(图片来自网络)
假设两个指针在z点相遇。则
a. 指针1走过路程为a + b;指针2走过的路程为 a+b+c+b
b. 因为指针2的速度是指针1的两倍,则有2(a+b) = a+b+c+b => a = c
c. 因此,当两个指针在z点相遇之后,可以让指针1指向链表起点x,然后两个指针每次分别都走一步
当两个指针再次相遇的时候,即为环的起点,即Y点
代码:
/** * 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);};ListNode* Solution::detectCycle(ListNode *head) { if (NULL == head) { return NULL; } ListNode *tmpHeadOne = head; ListNode *tmpHeadTwo = head; int step = 0; bool isCycle = false; while ((tmpHeadOne != NULL) && (tmpHeadTwo != NULL)) { if ((step != 0) && (tmpHeadOne == tmpHeadTwo)) { isCycle = true; break; } step++; tmpHeadOne = tmpHeadOne->next; tmpHeadTwo = tmpHeadTwo->next; if (tmpHeadTwo != NULL) { tmpHeadTwo = tmpHeadTwo->next; } } if (!isCycle) { return NULL; } tmpHeadOne = head; while (tmpHeadOne != tmpHeadTwo) { tmpHeadOne = tmpHeadOne->next; tmpHeadTwo = tmpHeadTwo->next; } return tmpHeadOne;}
0 0
- [LeetCode 第11题] -- Linked List Cycle II
- 第10题 Linked List Cycle II
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- VMware虚拟机下载
- 第十五周项目1:打入“内部”寻“内幕”
- ubuntu 14.10 安装 nodejs 和 npm
- DMA配置
- 如何给Android添加中文
- [LeetCode 第11题] -- Linked List Cycle II
- linux系统管理
- 天声人語 20141214
- 舞蹈课
- 一个网页通用的测试用例
- 使用Nexus创建私服
- 基于HTTPS协议的12306抢票软件设计与实现--相关接口以及数据格式
- 嵌入式软件开发书籍
- 深入理解Java虚拟机笔记---方法调用