C++怎么解決單鏈表中的環(huán)問題

本文小編為大家詳細(xì)介紹“C++怎么解決單鏈表中的環(huán)問題”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“C++怎么解決單鏈表中的環(huán)問題”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來學(xué)習(xí)新知識(shí)吧。

創(chuàng)新互聯(lián)公司是一家集網(wǎng)站建設(shè),貴南企業(yè)網(wǎng)站建設(shè),貴南品牌網(wǎng)站建設(shè),網(wǎng)站定制,貴南網(wǎng)站建設(shè)報(bào)價(jià),網(wǎng)絡(luò)營銷,網(wǎng)絡(luò)優(yōu)化,貴南網(wǎng)站推廣為一體的創(chuàng)新建站企業(yè),幫助傳統(tǒng)企業(yè)提升企業(yè)形象加強(qiáng)企業(yè)競(jìng)爭(zhēng)力??沙浞譂M足這一群體相比中小企業(yè)更為豐富、高端、多元的互聯(lián)網(wǎng)需求。同時(shí)我們時(shí)刻保持專業(yè)、時(shí)尚、前沿,時(shí)刻以成就客戶成長自我,堅(jiān)持不斷學(xué)習(xí)、思考、沉淀、凈化自己,讓我們?yōu)楦嗟钠髽I(yè)打造出實(shí)用型網(wǎng)站。

單鏈表中的環(huán)

Example 1:

Input: head = [3,2,0,-4], pos = 1

Output: true

Explanation: There is a cycle in the linked list, where tail connects to the second node.

C++怎么解決單鏈表中的環(huán)問題

Example 2:

Input: head = [1,2], pos = 0
Output: true
Explanation: There is a cycle in the linked list, where tail connects to the first node.

C++怎么解決單鏈表中的環(huán)問題

Example 3:

Input: head = [1], pos = -1
Output: false
Explanation: There is no cycle in the linked list.

C++怎么解決單鏈表中的環(huán)問題

Follow up:

Can you solve it using O(1) (i.e. constant) memory?

這道題是快慢指針的經(jīng)典應(yīng)用。只需要設(shè)兩個(gè)指針,一個(gè)每次走一步的慢指針和一個(gè)每次走兩步的快指針,如果鏈表里有環(huán)的話,兩個(gè)指針最終肯定會(huì)相遇。實(shí)在是太巧妙了,要是我肯定想不出來。代碼如下:

C++ 解法:

class Solution {
public:
    bool hasCycle(ListNode *head) {
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
        return false;
    }
};

Java 解法:

public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head, fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) return true;
        }
        return false;
    }
}

讀到這里,這篇“C++怎么解決單鏈表中的環(huán)問題”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道。

網(wǎng)頁標(biāo)題:C++怎么解決單鏈表中的環(huán)問題
文章出自:http://bm7419.com/article12/jceegc.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供標(biāo)簽優(yōu)化、關(guān)鍵詞優(yōu)化服務(wù)器托管、外貿(mào)網(wǎng)站建設(shè)、虛擬主機(jī)商城網(wǎng)站

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)

成都定制網(wǎng)站建設(shè)