Tag: The entry point to determine if a ring is found
650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7F/63/wKiom1ccqILwzLapAAB5HL-0XE8203.png "title=" Untitled. 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{//for Security Private:listnode (const listnode& l) {}listnode<t>& operator= ( LISTNODE&NBSP;L) {}public://program limit 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;}};/ /determine if the linked list has a ring 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;//so we from the link table head, and meet the point of each set a pointer,//each step, two pointers must meet, and meet 1th is the ring entry point. One from the beginning, the other from the point of encounter to walk in the ring,//fast pointer less than the slow pointer x, when they meet the first node is the entry point 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);//Build Ring if (Checkiscircle (L1._head)) {cout << (Searchcircleaccess (l1._head))->_ Data << endl;}}
Run Result: The data for the found entry point is 6
This article is from the "Small Stop" blog, please be sure to keep this source http://10541556.blog.51cto.com/10531556/1767284
Determine if the chain list has a ring, and if it has a ring, find the entry point of the ring