对于单链表的逆置一般有两种方法:
第一种用非递归法,利用辅助指针,其时间复杂度为O(n)
Node* Reverse() //单链表的逆置
{
Node* pre = _head;
Node* cur = pre->_next;
Node* next = NULL;
if(_head == NULL && _head->_next ==NULL)
{
return 0;
}
else
{
while(cur != NULL)
{
next = cur->_next;
cur->_next = pre;
pre = cur;
cur = next;
}
_head->_next = NULL;
_head = pre;
return _head;
}
}
第二种方法用递归法
void Reverse(Node* cur,List<T>& s)
{
cur = s._head;
if( (NULL==cur)||(NULL==cur->_next) )
{
s._head=cur;
}
else
{
Node* next=cur->_next;
Reverse(next,s._head); //递归逆置后继结点
next->_next = cur; //将后继结点指向当前结点。
cur->_next = NULL;
}
}
递归方法还是比较难以理解的,知道栈帧的概念的话会容易很多。每次函数调用都会在栈空间push一块空间,这个空间会保存该函数的形参和局部变量,当函数结束后,才会pop出这块空间。递归会占用更多的内存空间,而且函数调用会产生更多操作,时间开销很大。当然,并不排除有些编译器会优化掉递归的函数调用过程。所以,递归方法并不推荐。