Leedcode10-linked-list-cycle-ii
生活随笔
收集整理的這篇文章主要介紹了
Leedcode10-linked-list-cycle-ii
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
判斷是不是循環鏈表,如果是,返回它的第一個結點
首先判斷,判斷完之后,遍歷循環鏈表,將它的指針域置為空,則循環到鏈表的第一個結點時,由于指針域為空,返回
#include<iostream> #include<vector> using namespace std; /* Given a linked list, return the node where the cycle begins. If there is no cycle, returnnull. Follow up: Can you solve it without using extra space?*/ struct ListNode {int val;ListNode *next;ListNode(int x) : val(x), next(NULL) {} }; class Solution { public:bool hasCycle(ListNode *head) {if (head == NULL)return false;ListNode* faster = head;ListNode* slower = head;while (faster->next->next != NULL && faster->next != NULL) {slower = slower->next;faster = faster->next->next;if (faster == slower)return true;}return false;} }; //class Solution { //沒有通過所有測試用例 //public: // ListNode *detectCycle(ListNode *head) { // if (head == NULL) // return NULL; // ListNode* faster = head; // ListNode* slower = head; // while (faster->next->next != NULL && faster->next != NULL) { // slower = slower->next; // faster = faster->next->next; // if (faster == slower) //當他兩第一輪相同時,正好是最后一個結點 // return slower; // } // return NULL; // } //}; class Solution { public:bool hasCycle(ListNode *head) {ListNode *fast = head;ListNode *slow = head;while (fast != NULL && fast->next != NULL) {fast = fast->next->next;slow = slow->next;if (fast == slow)return true;}return false;}ListNode *detectCycle(ListNode *head) {if (hasCycle(head)) {ListNode *temp = head;while (head->next) {temp = head->next;head->next = NULL;head = temp;}return head;}else {return NULL;}} };?
總結
以上是生活随笔為你收集整理的Leedcode10-linked-list-cycle-ii的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: opencv32-基于距离变换和分水岭的
- 下一篇: mysql添加用户权限报1064 - Y