首页 > 学院 > 开发设计 > 正文

leecode 解题总结:141. Linked List Cycle

2019-11-08 02:49:07
字体:
来源:转载
供稿:网友
#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完成分析:分析一个链表是否有环,可以通过设置快慢指针的方式,快指针每次走两步,满指针每次走一步,如果某一时刻,快指针=慢指针,则存在环*/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;			}			//说明快指针下一个指针为空,链表已经遍历完了,不可能有环			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;}
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表