[leetcode 141] Linked List Cycle----判断链表是否为循环链表
来源:互联网 发布:军人网络保密自查自纠 编辑:程序博客网 时间:2024/05/17 01:52
Question:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断一个链表是否为循环链表,只要有NULL出现就不是循环链表。
方法:设置两个指针,第一个指针从头开始走两步每次,第二个指针每次从头开始走一步;如果第一个指针追上了第二个指针这说明是循环链表;否则不是循环链表。
代码如下:
<span style="font-size:14px;">/** * 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) { if(head == NULL || head->next == NULL) return false; ListNode* pre = head->next->next; ListNode* last = head; if(pre == NULL) return false; else{ while(pre != last){ if(pre->next != NULL && pre->next->next != NULL){ pre = pre->next->next; last = last->next; } else return false; } return true; } }};</span>
0 0
- [leetcode 141] Linked List Cycle----判断链表是否为循环链表
- (LeetCode)Linked List Cycle --- 判断循环链表
- leetcode--Linked List Cycle--判断链表是否有环
- Leetcode Linked List Cycle 循环链表
- [LeetCode-141] Linked List Cycle(判断链表是否有环)
- leetcode解题之141# Linked List Cycle Java版 (判断链表是否有环)
- 判断链表是否有环 Linked List Cycle, Linked List Cycle II
- LeetCode 141 Linked List Cycle(循环链表)(HashSet/Linked List)
- 判断链表是否有环 Linked List Cycle
- Linked List Cycle --判断链表是否有环
- Linked List Cycle 判断链表是否有环
- Linked List Cycle:判断链表是否有环
- LeetCode | Linked List Cycle(判断链表是否有环)
- LeetCode OJ 之 Linked List Cycle (判断链表是否有环)
- LeetCode OJ 之 Linked List Cycle II(判断链表是否有环 - 二)
- 【leetcode】Linked List Cycle II,判断链表是否有环
- 【Leetcode】141. Linked List Cycle-判断链表是否有环
- Leetcode Linked List Cycle II 循环链表入口
- ECMAScript5的新特性:案例
- 分享2015年底做的一个EDM案例-ACE酒店EDM营销
- Spring中AOP基于Annotation的零配置(2)
- web打印
- [JM] 如何结合标准看JM代码(JM86)
- [leetcode 141] Linked List Cycle----判断链表是否为循环链表
- day05 网络编程(二)
- 项目4:百钱买百鸡
- 12c_Data redaction 数据编写策略
- scala-String
- linux 命令之 fork[1]
- iOS堆与栈的区别
- HBase分布式集群搭建
- C++创建二叉树