#include <iostream>#include <stdio.h>#include <vector>#include <string>using namespace std;/*問題:Given a linked list, determine if it has a cycle in it.Follow up:Can you solve it without using extra space?16:48~16:48,16:54完成分析:分析一個鏈表是否有環(huán),可以通過設置快慢指針的方式,快指針每次走兩步,滿指針每次走一步,如果某一時刻,快指針=慢指針,則存在環(huán)*/struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {}};class Solution {public: bool hasCycle(ListNode *head) { if(!head) { return false; } ListNode* slow = head; ListNode* fast = head->next; bool isFind = false; while(fast && slow) { if(slow == fast) { isFind = true; break; } slow = slow->next; if(fast->next) { fast = fast->next->next; } //說明快指針下一個指針為空,鏈表已經遍歷完了,不可能有環(huán) else { break; } } return isFind; }};void PRint(vector<int>& result){ if(result.empty()) { cout << "no result" << endl; return; } int size = result.size(); for(int i = 0 ; i < size ; i++) { cout << result.at(i) << " " ; } cout << endl;}void process(){ vector<int> nums; int value; int num; Solution solution; vector<int> result; while(cin >> num ) { nums.clear(); for(int i = 0 ; i < num ; i++) { cin >> value; nums.push_back(value); } }}int main(int argc , char* argv[]){ process(); getchar(); return 0;}
新聞熱點
疑難解答