程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> (LeetCode OJ) 141. Linked List Cycle

(LeetCode OJ) 141. Linked List Cycle

編輯:C++入門知識

(LeetCode OJ) 141. Linked List Cycle


141. Linked List Cycle

My Submissions

Question

Total Accepted: 88665 Total
Submissions: 241622 Difficulty: Medium

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

Can you solve it without using extra space?

Subscribe to see which companies asked this question

Hide Tags
Linked List Two
Pointers

Hide Similar Problems
(M) Linked List Cycle II

 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
 //思路首先:如果有環?遍歷鏈表將無法走完,如果無環終會走到尾為NULL的位置
 //讓一個指針每次走一個,一個指針每次走兩個位置,如果其中一個為NULL則無環,如果相遇了
 //則有環
class Solution {
public:
    bool hasCycle(ListNode *head) {
        if(head==NULL)
            return false;
        ListNode *showNode=head;
        ListNode *fastNode=head;
        while(true)
        {
            if(showNode->next!=NULL)
                showNode=showNode->next;
            else
                return false;
            if(fastNode->next!=NULL && fastNode->next->next!=NULL)    
                fastNode=fastNode->next->next;
            else
                return false;    
            if(showNode==fastNode)
                return true;
        }
        return false;
    }
};

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved