题目:给你一个数字链表。。。链表到头之后又会从头开始(循环链表)。请写出寻找链表中最小数字的最高效算法。找出此链表中的任意给定数字。链表中的数字总是不断增大的,但是你不知道循环链表从何处开始。例:38, 40, 55, 89, 6, 13, 20, 23, 36.
程序:#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
//template<class T>
class node{
int value;
node* next;
public:
node(int v=0,node* n=0):value(v),next(n){}
void s_val(int v){value=v;}
void s_nex(node* n){next=n;}
int g_val(){return value;}
node* g_nex(){return next;}
friend ostream& operator<<(ostream&,const node&);
};
//template<class T>
class ran_ring{
node* head;
node* tail;
int size;
node* start;
public:
ran_ring(node* n=0);
~ran_ring();
void s_sta();
void push_back(int);
node* g_head();
void show_order();
friend ostream& operator<<(ostream&,const ran_ring&);
};
int main(){
ran_ring ring;
int temp;
while(cin>>temp)
ring.push_back(temp);
ring.s_sta();
cout<<ring;
cout<<*(ring.g_head());
return 0;
}
ostream& operator<<(ostream& os,const node& n){
os<<n.value<<' ';
return os;
}
ran_ring::ran_ring(node* n){
if(n)
size=1;
else
size=0;
head=n;
tail=head;
start=head;
}
ran_ring::~ran_ring(){
tail=head;
while(tail->g_nex()){
delete head;
head=tail->g_nex();
tail=head;
}
head=0;
tail=0;
}
void ran_ring::s_sta(){
int off=int(size*rand()/(RAND_MAX+1.0));
cout<<off;
for(int i=0;i<off;++i){
start=start->g_nex();
}
}
void ran_ring::push_back(int v){
if(size){
tail->s_nex(new node(v,head));
tail=tail->g_nex();
}else{
head=new node(v);
tail=head;
head->s_nex(tail);
start=head;
}
++size;
}
node* ran_ring::g_head(){
node* t1=start;
node* t2=t1->g_nex();
while(t1->g_val()<t2->g_val()){
t1=t2;
t2=t2->g_nex();
}
return t2;
}
void ran_ring::show_order(){
cout<<*head;
}
ostream& operator<<(ostream& os,const ran_ring& r){
node* temp=r.start->g_nex();
os<<*(r.start);
while(temp!=r.start){
os<<*temp;
temp=temp->g_nex();
}
return os;
}