leetcode-141-Linked List Cycle
2015-06-22 22:04
453 查看
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?
判断链表是否有环
/** * 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) { //STL里的set 每插入一个节点 判断是否成功插入 set<ListNode*>s; int n=0; while(head){ n++; s.insert(head); if(s.size()!=n) return true; // 没有成功插入 有环 head=head->next; } return false; // 每一次都成功插入了 证明每个节点都不一样 即无环 }
/** * 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||!head->next) return false; ListNode* fast=head->next->next; while(fast!=head){ // 采用快慢指针 fast每次走两步 head走一步 若有环 则必定相遇 if(!fast||!fast->next) return false; fast=fast->next->next; head=head->next; } return true; } };
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # python # @return a boolean def hasCycle(self, head): if not head or not head.next: return False fast=head.next.next while fast!=head: if not fast or not fast.next: return False head=head.next fast=fast.next.next return True;
相关文章推荐
- Collection接口
- CSU1657: Ways
- Collection接口
- 第六章
- Winsocket编程一般步骤-服务端编程
- 谈谈iOS中粘性动画以及果冻效果的实现
- List接口
- CentOS6.5安装LAMP环境APACHE的安装
- 函数指针数组指针实例
- 只用getchar函数读入一个整数(算法竞赛入门经典 完整版)
- List接口
- UVa11054 - Wine trading in Gergovia UVA
- 2015062201 - 成长
- 第一阶段冲刺站立会议报告一(补)
- 安装并配置Hadoop伪分布模式
- String类转换功能
- 学习计划
- String类转换功能
- NABCD分析
- iframe通信问题及自适应高度