您好,登錄后才能下訂單哦!
#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; } }; //判斷鏈表是否帶環(huán) 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; //于是我們從鏈表頭、與相遇點(diǎn)分別設(shè)一個(gè)指針, //每次各走一步,兩個(gè)指針必定相遇,且相遇第一點(diǎn)為環(huán)入口點(diǎn)。 //一個(gè)從頭走,另一個(gè)從相遇點(diǎn)開始在環(huán)里走, //快指針比慢指針少走x,當(dāng)它們相遇的第一個(gè)節(jié)點(diǎn)就是入口點(diǎn) 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);//構(gòu)建環(huán) if (CheckIsCircle(l1._head)) { cout << (SearchCircleAccess(l1._head))->_data << endl; } }
運(yùn)行結(jié)果:找到的入口點(diǎn)的數(shù)據(jù)為6
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。