LeetCode--Linked List Cycle
来源:互联网 发布:d3.js的作用 编辑:程序博客网 时间:2024/05/19 00:55
Linked List Cycle
Total Accepted: 17148 Total Submissions: 49300My SubmissionsGiven 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) { /* 1. 空链表不成环 2. 一个节点自环 3. 一条链表完整成环 */ if(head==NULL)return false; if(head->next==NULL)return false; if(head->next==head)return true; ListNode* y=head->next; ListNode* x=head->next->next; while(x!=NULL && y!=NULL) { x=x->next; if(x==NULL)break; x=x->next; y=y->next; if(x==y)break; } return x==y; } };标准做法是使用两个指针,一个每次往前走2步,一个每次往前走1步,如果两个指针相遇,即说明链表有环,时间复杂度为O(N),空间复杂度为O(1)。
0 0
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- [LeetCode]Linked List Cycle
- LeetCode | Linked List Cycle
- Leetcode: Linked List Cycle
- LeetCode: Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode] - Linked List Cycle
- LeetCode - Linked List Cycle
- [LeetCode]Linked List Cycle
- 【LeetCode】Linked List Cycle
- Linked List Cycle - LeetCode
- 【LeetCode】Linked List Cycle
- Linked List Cycle -- LeetCode
- Iterator和Iterable的 新理解--一个神奇的接口
- ado.net基础代码
- java.text.DecimalFormat学习笔记
- 测试各种数据类型字节长度
- Davinci DM6446开发攻略——linux-2.6.18移植
- LeetCode--Linked List Cycle
- 第十一讲 页面布局及母版页
- ios推送常用方法
- Node.js 入门简介
- TI C66x DSP 系统events及其应用 - 5.3(Interrupt)
- 继承的基本演示
- 局域网聊天中如何实现 CStdioFile 按行读取写入
- 第十二讲 N层架构在ASP.NET中的应用(一)
- C3P0数据库连接池源代码