oj141. Linked List Cycle
来源:互联网 发布:腾讯有网络币不 编辑:程序博客网 时间:2024/06/08 11:19
Given a linked list, determine if it has a cycle in it.
翻译:给定一个链表,确定它是否有一个循环。
超时思路:
新建一个list来装链表节点,若新节点指向的下一个节点已经存在list中,则返回真
public boolean hasCycle(ListNode head) { List<ListNode> l = new ArrayList<ListNode>(); l.add(head); if(head == null) return false; ListNode nextNode = head.next; while(nextNode!= null){ if(l.contains(nextNode)) return true; l.add(nextNode); nextNode = nextNode.next; } return false; }答案思路:快慢指针
- 用两个指针,慢指针和快指针
- 慢指针每次走一步,快指针每次走两步
- 如果两个指针相遇,则有循环。
public boolean hasCycle(ListNode head) { if(head == null) return false; ListNode walker = head; ListNode runner = head; while(runner.next != null && runner.next.next != null){//快指针走的快,这里要判断快指针是否为空。 walker = walker.next; runner = runner.next.next; if(walker == runner) return true; } return false; }
0 0
- oj141. Linked List Cycle
- leetcode Linked List Cycle & Linked List Cycle ||
- Linked List Cycle II Linked List Cycle
- 【LeetCode】Linked List Cycle
- Leetcode: Linked List Cycle
- Leetcode Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle
- Linked List Cycle II
- Leetcode: Linked List Cycle
- LeetCode:Linked List Cycle
- Linked List Cycle II
- Linked List Cycle
- Linked List Cycle II
- [LeetCode]Linked List Cycle
- Linked List Cycle
- 122.Best Time to Buy and Sell Stock II
- 记忆化搜索——BZOJ4562/Luogu3183 [HAOI2016]食物链
- Spring学习-31:Spring中的事务管理之手动编码的方式
- 微信小程序demo,
- 图像传输
- oj141. Linked List Cycle
- ubuntu安装和查看已安装
- 数组排序,奇数在前,偶数在后
- 小技巧记录
- java根据ftl模板导出word文档
- 关于mysql如何创建多用户
- Telnet与SSH协议
- mysql字符集
- 机器学习中训练数据集,交叉验证数据集,测试数据集的作用