Linked List Cycle II
来源:互联网 发布:mac sierra是什么 编辑:程序博客网 时间:2024/05/21 12:45
<pre name="code" class="cpp">/** * 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* h1 = head, *h2 = head; //h1走一步,h2走两步,两个值必定会相遇 while(NULL != h1 && NULL != h2) { h1 = h1->next; h2 = h2->next; if(h2 == NULL) return NULL; h2 = h2->next; if(h1 == h2)//如果相遇,则表示有环。 { h1 = head; while(h1 != NULL && h2 != NULL)//一个从头走,一个从之前相遇的位置走,则必定会在第一个相交点遇见。 { if(h1 == h2)//说明head就是第一个相遇点 { return h1; } h1 = h1->next; h2 = h2->next; } break; } } return NULL; }};
0 0
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- 创业项目开发阶段性总结
- error: No resource identifier found for attribute 'format24Hour' in package 'android'
- [LeetCode][Java] Longest Common Prefix
- JS原生函数总结
- linux shell中 if else以及大于、小于、等于逻辑表达式介绍
- Linked List Cycle II
- FreeMarker语法知识
- Java基础日记———IO流(下)
- Android-优化UI性能(1)-减少主线程的阻塞时间
- 二叉搜索树(C++)
- CF 3B Lorry
- 字符串初始化
- 百度移动统计的应用
- 前端小tips之标签