LeetCode——Linked List Cycle
来源:互联网 发布:jdbc连接数据库 编辑:程序博客网 时间:2024/06/06 00:24
LeetCode——Linked List Cycle
#141
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
这一题的目的是判断链表中是否有环。一个思路是利用哈希表。如果遍历过的结点已经存在了哈希表,则说明有环。
先用java先,因为java中有hash结构,写起来比较方便。
- Java
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public boolean hasCycle(ListNode head) { Set<ListNode> nodesSeen = new HashSet<>(); while (head != null) { if (nodesSeen.contains(head)) { return true; } else { nodesSeen.add(head); } head = head.next; } return false; }}
还有一种解法,设置两个指针,一个一次走一步,一个一次走两步,如果存在环,则两个指针会相遇。
- C++
/** * 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 *slow = head, *fast = head; while (fast && fast->next) { slow = slow->next; fast = fast->next->next; if (slow == fast) return true; } return false; }};
- Java
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public boolean hasCycle(ListNode head) { ListNode slow = head, fast = head; while (fast != null && fast.next != null) { slow = slow.next; fast = fast.next.next; if (slow == fast) return true; } return false; }
阅读全文
0 0
- LeetCode——Linked List Cycle
- LeetCode——Linked List Cycle II
- LeetCode——Linked List Cycle
- Linked List Cycle —— Leetcode
- LeetCode——Linked List Cycle II
- leetcode 141 —— Linked List Cycle
- LeetCode题解——Linked List Cycle
- LeetCode——141. 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 II——单链表中的环
- [算法][LeetCode]Linked List Cycle & Linked List Cycle II——单链表中的环
- LeetCode——141. Linked List Cycle && 142. Linked List Cycle II
- leetcode Linked List Cycle & Linked List Cycle ||
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Android 二次封装网络加载框架
- 四、枚举,递推、迭代法初步学习
- 选择文件与获取选中文件绝对路径
- scrapy shell 爬取一些网站不响应
- idea中导入maven项目时修改maven地址
- LeetCode——Linked List Cycle
- C语言“翻译”C++结构体中的成员函数
- Leetcode:226. Invert Binary Tree
- tps(第三人称射击游戏) 1.相机
- Vue 使用过程中的问题记录
- Java(32):哈希表 的原理和应用
- Android深入--Handler机制简析(Handler、Looper、MessageQueue)
- JAVA 垃圾收集器和回收策略
- java 中的 wait()方法和 sleep()方法的区别