【LeetCode】之Linked List Cycle
来源:互联网 发布:淘宝的钻石展位是什么 编辑:程序博客网 时间:2024/05/22 12:54
Given a linked list, determine if it has a cycle in it.
此题目的在于判断一个链表是否是一个循环链表。
思路:
1.先定义两个节点指针first和second;
2.first每次走一步,second每次走两步;
3.若second && second->next为NULL,则返回false,此判断是因为如果second为NULL,则
second->next就会抛出异常,同样要判断second->next是否为NULL,不然second->next->next也会抛出异常;
4.否则,如果first == second ,则返回true。
/** * 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 *first = head; ListNode *second = head; while(second && second->next){ first = first->next; second = second->next->next; if(first == second) return true; } return false; }};
0 0
- 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 II
- leetcode Linked List Cycle & Linked List Cycle ||
- 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
- 欢迎使用CSDN-markdown编辑器
- android做新闻客户端用到得第三包
- scala实现设计模式之命令模式
- 用自定义缓存区的方式实现文件的移动
- 【坑】javascript中匿名函数表达式的估值操作
- 【LeetCode】之Linked List Cycle
- 用两个栈实现队列
- 动态增加文本框
- CopyOnWriteArrayList与Collections.synchronizedList的性能对比
- 《剑指Offer》面试题:数值的整数次方
- scala实现设计模式之解释器模式
- 对于内存的一点笔记
- js动态的在页面上增加或删除一个文本框
- Vysor 情怀玩法 (番外篇)--调戏妹子