博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[Linked List]Linked List Cycle,Linked List Cycle II
阅读量:5366 次
发布时间:2019-06-15

本文共 1922 字,大约阅读时间需要 6 分钟。

一.Linked List Cycle
Total Accepted: 85115 Total Submissions: 232388 Difficulty: Medium

 

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) {        if(head==NULL || head->next==NULL){            return false;        }        ListNode *first =head;        ListNode *second = head;        while(first && second)        {            first = first->next;            second = second->next;            if(second){                second = second->next;            }            if(first==second){                return true;            }        }        return false;    }};
Next challenges: 
 
二.Linked List Cycle II
Total Accepted: 61662 Total Submissions: 196038 Difficulty: Medium

 

Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Note: Do not modify the linked list.

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:    ListNode *detectCycle(ListNode *head) {        ListNode* slow=head,*fast=head;        bool has_cycle = false;        while(slow && fast){            slow = slow->next;            fast = fast->next;            if(fast){                fast=fast->next;            }            if(slow == fast && slow){                has_cycle = true;                break;            }        }        ListNode* p = has_cycle ? head:NULL;        while(has_cycle && p!=slow){            p = p->next;            slow = slow->next;        }        return p;    }};
Next challenges:     
 
 
参考:

转载于:https://www.cnblogs.com/zengzy/p/5041012.html

你可能感兴趣的文章
平安科技移动开发二队技术周报(第九期)
查看>>
JS window.open()属性
查看>>
Oracle【二维表管理:约束】
查看>>
2017-2018-1 20155307 《信息安全系统设计基础》第5周学习总结
查看>>
微软职位内部推荐-Principal Dev Manager for Windows Phone Apps
查看>>
jquery改变元素属性值(转)
查看>>
模板题 Truck History poj1789
查看>>
部署zookeeper实践
查看>>
git回退版本
查看>>
mysql 1093错误
查看>>
io流2
查看>>
测试作业
查看>>
SQLite与SQL差异
查看>>
什么是路由器?
查看>>
SQL Server 性能优化之——系统化方法提高性能
查看>>
《额尔古纳河右岸》读书笔记
查看>>
使用RMAN Active duplicate创建异地auxiliary Database
查看>>
self.location.href的具体用法(转)
查看>>
软件工程第三次作业
查看>>
Introducing my blog
查看>>