每天一道leetcode141-環形鏈表
阿新 • • 發佈:2018-11-08
兩個指針 output gradient 主任 list comm 定義 style 交流
考試結束,班級平均分只拿到了年級第二,班主任於是問道:大家都知道世界第一高峰珠穆朗瑪峰,有人知道世界第二高峰是什麽嗎?正當班主任要繼續發話,只聽到角落默默想起來一個聲音:”喬戈裏峰”
前言
2018.11.8號打卡
明天的題目:
https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list/
題目
每天一道leetcode141-環形鏈表
分類:鏈表
中文鏈接:
https://leetcode-cn.com/problems/linked-list-cycle/description/
英文鏈接
https://leetcode.com/problems/linked-list-cycle/description/
題目詳述
給定一個鏈表,判斷鏈表中是否有環。
進階:
你能否不使用額外空間解決此題?
題目詳解
思路
- 使用兩個指針,一個快指針,一個慢指針;
- 快的每次走兩步,慢的每次走一步,如果有環,那麽快的肯定可以追上慢點,兩者相等
代碼
1/**
2 * Definition for singly-linked list.
3 * class ListNode {
4 * int val;
5 * ListNode next;
6 * ListNode(int x) {
7 * val = x;
8 * next = null;
9 * }
10 * }
11 */
12public class Solution {
13 public boolean hasCycle(ListNode head) {
14 if(head == null || head.next == null)
15 return false;
16 ListNode fast = head.next;
17 ListNode slow = head;
18 while(slow != null && fast != null)
19 {
20 if (fast == slow)
21 return true;
22 slow = slow.next;
23 if(fast.next != null)
24 fast = fast.next.next;
25 else
26 return false;
27 }
28 return false;
29 }
30}
代碼講解
- 16-17行定義快慢指針
- 20-21行如果快指針與慢指針相遇,那麽說明有環;
- 22-26行 快的走兩步,慢的每次走一步
結束語
2018.11.8號打卡
作者喬戈裏親歷2019秋招,哈工大計算機本碩,百度準入職java工程師,歡迎大家關註我的微信公眾號:程序員喬戈裏,公眾號有3T編程資源,以及我和我朋友(準入職百度C++工程師)在秋招期間整理的近200M的面試必考的java與C++面經,並有每天一道leetcode打卡群與技術交流群,歡迎關註。
每天一道leetcode141-環形鏈表