leetcode 141. Linked List Cycle
生活随笔
收集整理的這篇文章主要介紹了
leetcode 141. Linked List Cycle
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
?
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
?
題意:
? ? ? 判斷一個鏈表是否有環。
?
解決方案:
? ? ? 雙指針,快指針每次走兩步,慢指針每次走一步,
? ? ? ? ? ? 如果有環,快指針和慢指針會在環內相遇,fast == slow,這時候返回true。
? ? ? ? ? ? 如果沒有環,返回false.
?
/*** 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 fast = head, slow = head;if(head == null || head.next == null) return false;while(fast != null && fast.next != null){fast = fast.next.next;slow = slow.next;if(fast == slow){return true;}}return false;} }?
轉載于:https://www.cnblogs.com/iwangzheng/p/5695174.html
總結
以上是生活随笔為你收集整理的leetcode 141. Linked List Cycle的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 七猫小说app怎么改阅读字体
- 下一篇: 在android studio中创建He