#include <iostream>using namespace Std;template<typename _ty>class node{public:node (_ty _X=_Ty ()): _Data ( _x), _next (NULL) {}int _data; Node<_ty> *_next;}; Template<typename _ty>class list{public:list () {_first = new node<_ty> ();} void Insert (int _x) {node<_ty> *_s = new node<_ty> (_x); _s->_next = _first->_next;_first->_next = _S;} node<_ty>* iscircle ()//Determine if it is a ring, and return the first meeting node address {node<_ty> *_p= _first; Node<_ty> *_q= _first;while (_p!=null && _p->_next!=null) {_p=_p->_next->_next;_q=_q->_ Next;if (_P==_Q) return _p;} return NULL;} void setcircle (int _x)//Set the position of the ring. {node<_ty>* _p = _first; Node<_ty>*_q = _first;while (_q->_next!=null) {_q=_q->_next;} for (int _i=0;_i<_x;_i++) {_p=_p->_next;} _q->_next=_p;} int getcirclelength ()//the size of the ring {node<_ty> *_p = _first; node<_ty> *_q = _first;int _a=0;while (1) {_p=_p->_next->_next;_q=_q->_next;_a++;if (_P==_Q) break;} return 2*_a-_a;} int getcircle ()//Gets the number of nodes from the ring point to the start node. {node<_ty> *_p = Iscircle (); node<_ty> *_q = _first;int _a=0;while (_p!=_q) {_p=_p->_next;_q=_q->_next;_a++;} return _a;} /*void Show () {node<_ty> *_p = _first;while (_p->_next!=null) {cout<<_p->_next->_data<< ""; _p=_p->_next;} Cout<<endl;} */private:node<_ty> *_first;}; int main () {list<int> list;for (int i=0;i<20;i++) {List. Insert (i);} List. Setcircle (10);//Set the position of the ring if (list. Iscircle ()) {cout<< "There are rings! "<<endl;} else{cout<< "no Ring" <<ENDL;} cout<< "The position of the ring is:" <<list. Getcircle () <<endl; The length of the cout<< "ring is:" <<list. Getcirclelength () <<endl; return 0;}
Impressions: 1. Determine if there is a ring with a fast or slow pointer.
2. After the first encounter, the fast pointer changes speed from two nodes at a time into a node, the slow pointer starts from the beginning, and when they meet again the node is the ring start position.
3. The length of the ring is the number of nodes that the slow pointer passes when the first speed pointer encounters, because the fast pointer speed is twice times the slow pointer, and the fast pointer distance-the slow pointer distance = the ring size.
C + + single-linked list operation for rings.