Leetcode 141. Linked List CycleJAVA语言
生活随笔
收集整理的這篇文章主要介紹了
Leetcode 141. Linked List CycleJAVA语言
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
| 1 2 3 | Given?a?linked?list,?determine?if?it?has?a?cycle?in?it. Follow?up: Can?you?solve?it?without?using?extra?space? |
題意:判斷鏈表有沒(méi)有環(huán)
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | /** ?*?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)?{ ????????///定義兩個(gè)快慢指針。有環(huán)的話快指針一定會(huì)和慢指針相遇。否則快指針就提前到尾巴了 ????????應(yīng)該是我那會(huì)的考研題ca ????????if(head==null?||?head.next==null?||?head.next.next==null)return?false; ????????ListNode?fast=head.next.next; ????????ListNode?slow=head.next; ????????while(fast!=slow){ ????????????if(fast.next!=null?&&?fast.next.next!=null){ ????????????????fast=fast.next.next; ????????????????slow=slow.next;???? ????????????}else{ ????????????????//fast提前走到了尾 ????????????????return?false; ????????????} ????????????? ????????} ????????return?true; ????} } |
PS:快慢指針。注意判斷邊界條件
本文轉(zhuǎn)自 努力的C 51CTO博客,原文鏈接:http://blog.51cto.com/fulin0532/1905474
總結(jié)
以上是生活随笔為你收集整理的Leetcode 141. Linked List CycleJAVA语言的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 实验
- 下一篇: Crash/Instance Recov