判斷鏈表是否帶環,若帶環,找到環的進入點

來源:互聯網
上載者:User

標籤:判斷是否帶環   找環的進入點   

650) this.width=650;" src="http://s5.51cto.com/wyfs02/M00/7F/63/wKiom1ccqILwzLapAAB5HL-0XE8203.png" title="無標題.png" alt="wKiom1ccqILwzLapAAB5HL-0XE8203.png" />

#pragma once#include<iostream>using namespace std;template<class T>struct LinkNode{T _data;LinkNode* _next;LinkNode(const T& x):_data(x), _next(NULL){}};template<class T>class ListNode{//為了安全性private:ListNode(const ListNode& l){}ListNode<T>& operator=(ListNode l){}public://程式限制LinkNode<T>* _head;public:ListNode():_head(NULL){}~ListNode(){while (_head){PopBack();}}void PushBack(const T& x){LinkNode<T>* tmp = new  LinkNode<T>(x);if (_head == NULL)_head = tmp;else{LinkNode<T>* cur = _head;while (cur->_next)cur = cur->_next;cur->_next = tmp;}}void PopBack(){if (_head == NULL)return;if (_head->_next == NULL){delete _head;_head = NULL;}else{LinkNode<T>* cur = _head;while (cur->_next&&cur->_next->_next){cur = cur->_next;}LinkNode<T>* del = cur->_next;cur->_next = NULL;delete del;}}LinkNode<T>* Search(const T& x){if (_head == NULL)return  NULL;LinkNode<T>*  cur = _head;while (cur->_data != x)cur = cur->_next;return cur;}};//判斷鏈表是否帶環template<typename T>bool CheckIsCircle(LinkNode<T>* head){if (head == NULL || head->_next == NULL)return false;LinkNode<T>* fast, *slow;fast = slow = head;while (fast&&fast->_next){fast = fast->_next->_next;slow = slow->_next;if (fast == slow)return true;}return false;}template<class T>LinkNode<T>* SearchCircleAccess(LinkNode<T>* head){if (head == NULL||head->_next==NULL)return NULL;LinkNode<T>* fast = head;LinkNode<T>* slow = head;while (fast&&fast->_next){fast = fast->_next->_next;slow = slow->_next;if (fast == slow)break;}slow = head;//於是我們從鏈表頭、與相遇點分別設一個指標,//每次各走一步,兩個指標必定相遇,且相遇第一點為環進入點。//一個從頭走,另一個從相遇點開始在環裡走,//快指標比慢指標少走x,當它們相遇的第一個節點就是進入點while (slow != fast){slow=slow->_next;fast = fast->_next;}return slow;}void Test1(){ListNode<int> l1;l1.PushBack(1);l1.PushBack(2);l1.PushBack(3);l1.PushBack(4);l1.PushBack(5);l1.PushBack(6);l1.PushBack(7);l1.PushBack(8);l1.PushBack(9);(l1.Search(9))->_next = l1.Search(6);//構建環if (CheckIsCircle(l1._head)){cout << (SearchCircleAccess(l1._head))->_data << endl;}}

運行結果:找到的進入點的資料為6

本文出自 “小止” 部落格,請務必保留此出處http://10541556.blog.51cto.com/10531556/1767284

判斷鏈表是否帶環,若帶環,找到環的進入點

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.