LeetCodeOJ. Linked List Cycle
来源:互联网 发布:我的淘宝如何换帐号 编辑:程序博客网 时间:2024/06/07 18:57
试题请参见: https://oj.leetcode.com/problems/linked-list-cycle/
题目概述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解题思路
数据结构典型例题: 使用快慢指针.
快指针遍历时, 一次遍历2个元素; 慢指针一次遍历1个元素.
若他俩不相等, 则不存在环.
遇到的问题
RunTime Error
遍历时, 请检查 fastNode->next 是否为NULL, 否则会出现Runtime Error.
源代码
/** * 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) { ListNode* fastNode = head; ListNode* slowNode = head; while ( fastNode != NULL && slowNode != NULL ) { if ( fastNode->next != NULL ) { fastNode = fastNode->next->next; } else { return false; } slowNode = slowNode->next; if ( fastNode == slowNode ) { return true; } } return false; }};
0 0
- LeetCodeOJ. Linked List Cycle
- LeetCodeOJ:206 Reverse Linked List
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Code[VS] 1022 覆盖
- 图论——最短路径
- sicily_1012 (计算几何)
- Code[VS] 1090 加分二叉树
- C语言指针系列四——指针与函数
- LeetCodeOJ. Linked List Cycle
- ENVI自学笔记一
- Android开发者必须知道的内存管理知识
- Code[VS] 3301 Square words
- Code[VS] 1436 孪生素数2
- Code[VS] 2046 孪生素数3
- 【Codechef】February Challenge 2015 Chef and Strings
- Code[VS] 1481 忠诚
- 编程笔记_JAVA_正则表达式工具