Leetcode: linked-list-cycle-ii
来源:互联网 发布:scott disick 知乎 编辑:程序博客网 时间:2024/06/07 20:44
题目:
Given a linked list, return the node where the cycle begins. If there is no cycle, return null.
Follow up:
Can you solve it without using extra space?
分析:
给定一个链表,返回这个链表中环的开始,若无环,那么返回null,并且不能有额外的空间。首先需要判断是否有环,定义两个指针slow和fast,slow每次前进一格,fast每次前进
两格,如果有环,那么这两个指针必然会相遇;如果没有环,那么直接返回null即可;在有环的情况下,将slow指针指向相遇节点,将fast指针指向开始节点,继续前进,这时两个
指针每次前进一格,当指针再次相遇的时候,就是环开始的位置。
具体代码如下:
/** * Definition for singly-linked list. * class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { public ListNode detectCycle(ListNode head) { ListNode meeting = meetingNode(head); if (meeting == null) return null; ListNode fast = head; ListNode slow = meeting; while(slow != fast){ fast = fast.next; slow = slow.next; } return fast; } public ListNode meetingNode(ListNode head){ if(head == null || head.next == null) return null; ListNode slow = head; ListNode fast = head; while(fast.next != null && fast.next.next != null){ slow = slow.next; fast = fast.next.next; if (slow == fast) return slow; } return null; }}
阅读全文
0 0
- 【LeetCode】 Linked List Cycle II
- Leetcode: Linked List Cycle II
- <Leetcode>Linked List Cycle II
- [LeetCode] Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode:Linked List Cycle II
- Leetcode Linked List Cycle II
- [LeetCode]Linked List Cycle II
- leetcode Linked List Cycle II
- LeetCode | Linked List Cycle II
- Leetcode: Linked List Cycle II
- [LeetCode] - Linked List Cycle II
- Leetcode: Linked List Cycle II
- LeetCode - Linked List Cycle II
- leetcode Linked List Cycle II
- Linked List Cycle II -- LeetCode
- LeetCode Linked List Cycle II
- [LeetCode] Linked List Cycle II
- MySQL慢查询日志与磁盘IO
- linux,ubuntu,linuxmint完美安装最新版qq
- Q&A——资源管理(三)
- Vue.js组件化开发实践
- caffe 相关--Blobs, Layers, and Nets: anatomy of a Caffe model
- Leetcode: linked-list-cycle-ii
- Q&A——资源管理(四)
- spark 2.1 CallerContext
- Opencv 多线程显示错误 [xcb] Unknown request in queue while dequeuing [xcb] Most likely this is a multi-thre
- &和global的妙用
- redis 学习笔记
- 索引
- REACT NATIVE 真正的路线,其实没那么难
- 项目部署到远程Linux服务器