LeetCode: Linked List Cycle [141]

來源:互聯網
上載者:User

標籤:leetcode   演算法   面試   

【題目】

Given a linked list, determine if it has a cycle in it.

Follow up:
Can you solve it without using extra space?


【題意】

    判斷一個單向鏈表是否有環


【思路】

    維護兩個指標p1和p2,p1每次向前移動一步,p2每次向前移動兩步
    如果p2能夠追上p1,則說明鏈表中存在環


【代碼】
/** * Definition for singly-linked list. * struct ListNode { *     int val; *     ListNode *next; *     ListNode(int x) : val(x), next(NULL) {} * }; */class Solution {public:    bool hasCycle(ListNode *head) {        ListNode*p1=head;        ListNode*p2=head;        while(p2){            //p1向前走一步            p1=p1->next;            //p2向前走兩部            p2=p2->next;            if(p2)p2=p2->next;            //判斷p2是否追上了p1            if(p2 && p2==p1)return true;        }        return false;    }};


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.