出个题目,O(n)时间里逆转单链表 补全函数。
补写reverse函数,实现链表逆转。
递归的,非递归的。
程序代码:#include
using namespace std;
struct Exception{
Exception(){cout<
};
template
struct node{
Type val;
node *next;
node(){next=NULL;}
node(Type v):val(v){next=NULL; }
friend ostream & operator< & n)
{
out<
return out;
}
};
template
class SList{
private:
node *hummy;
protected:
node * getPre(node *pointer)
{
try{
node * n;
for(n=hummy;n!=NULL;n=n->next)
{
if( n->next==pointer)
break;
}
if( pointer== hummy)
throw Exception();
return n;
}catch( Exception () )
{
cout<
return NULL;
}
}
node * getNext(node *pointer)
{
try{
if(pointer->next==NULL)
throw Exception ();
return pointer->next;
}catch( Exception e)
{
cout<
return NULL;
}
}
bool insert(node *pointer, Type v)
{
try
{
node *n=new node(v);
if( NULL == n )
throw Exception();
else
{
n->next=pointer->next;
pointer->next=n;
return true;
}
}catch (Exception e )
{
cout<
return false;
}
}
bool del(node *pointer)
{
try
{
if( pointer != hummy->next)
{
node * pre=getPre(pointer);
pre->next=pointer->next;
delete pointer;
pointer=NULL;
}
else
{
hummy->next=pointer->next;
delete pointer;
pointer=NULL;
}
}catch( Exception())
{
}
}
public:
SList(){ hummy=new node();}
SList(int n)
{
hummy=new node();
for( int i=0;i
{
Type m;
cin>>m;
insert(hummy,m);
}
}
friend void reverse( SList & s)
{
}
void travel()
{
node * n;
for( n=hummy->next; n!=NULL;n=n->next)
{
cout<
}
cout<
}
};
int main()
{
int m;
cin>>m;
SList sl(m);
sl.travel();
reverse(sl);
sl.travel();
return 0;
}