Day006:Linked List Cycle II
来源:互联网 发布:实名认证数据网 编辑:程序博客网 时间:2024/06/06 18:30
Problem:
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?
Difficulty:
Solution:
Read all the node of list,k mean the k node of a list,then from the head pointer to this node,count the number of next time.if the number is equal to k,the node is not the node we need,if the number is not equal to k,we find the node,and the list is a cycle.
/** * Definition for singly-linked list. * struct ListNode { * int val; * ListNode *next; * ListNode(int x) : val(x), next(NULL) {} * }; */using namespace std;class Solution {public: ListNode *detectCycle(ListNode *head) { if (head == nullptr || head->next == nullptr){ return NULL; } if(head->next == head){ return head; } int i = 0; int j = 0; int k = 0; ListNode* node=head; ListNode* node1=nullptr; while(true){ i = i + 1; j = 0; node1 = head; while(true){ j = j+ 1; if (node1 == node){ k = j; break; } node1 = node1->next; } if(i != k){ return node; } node = node->next; if (node == nullptr){ return NULL; } } }};
0 0
- Day006:Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Linked List Cycle II
- Oracle查询树型关系(start with connect by prior)
- openstack(m版)官网创建云主机过程
- HomeBrew安装
- 【JQuery学习总结2 】Jquery字符串, 数组(拷贝、删选、合并等), each循环,阻止冒泡,ajax出错,$.grep筛选,$.param序列化
- java面试
- Day006:Linked List Cycle II
- openwrt创建子端口
- c#mvc redirecttoaction 和redirect的区别
- ABIX.v6.69.01.Bilanguage.WinAll-LAXiTY\
- mysql-常用分析工具
- java设计模式--工厂方法模式
- java将阿拉伯数字转换为中文数字
- css元素分类
- Android中Toolbar (2)