首页 > 代码库 > Linked List Cycle [leetcode]
Linked List Cycle [leetcode]
#include<iostream> #include<string> #include<fstream> using namespace std; struct ListNode { int val; ListNode *next; ListNode(int x) : val(x), next(NULL) {} }; class Solution { public: bool hasCycle(ListNode *head) { ListNode* fast_walker = head; ListNode* slow_walker = head; while (fast_walker && slow_walker){ fast_walker = fast_walker->next; if (fast_walker) fast_walker = fast_walker->next; else break; slow_walker = slow_walker->next; if (slow_walker == fast_walker){ return true; } } return false; } }; /* 从命令行接受数据 初始化 链表 int main(){ ListNode* head = NULL; ListNode* tmp = head; int in = 0; while (cin >> in){ tmp->next = new ListNode(in); tmp = tmp->next; tmp->next = NULL; } Solution ss; ss.hasCycle(head); return 0; } */ //从文本文件中初始化链表 int main(){ fstream fin("test.txt"); ListNode* head(0);//此时并没有分配存储地址 ListNode* tmp = head;//此时相当于 tmp = NULL int in = 0; while (fin >> in){ if (!head) { head = new ListNode(in); tmp = head; } else{ while (tmp->next != NULL) tmp = tmp->next; tmp->next = new ListNode(in); tmp = tmp->next; tmp->next = NULL; } } //制造一个环 tmp->next = head->next; Solution ss; bool retult = ss.hasCycle(head); system("pause"); return 0; }
Linked List Cycle [leetcode]
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。