把单向链表中元素逆置(不允许申请新的结点空间)

来源:百度知道 编辑:UC知道 时间:2024/05/24 14:05:11
数据结构方面知识

设first指针指向单链表的第一个结点,试设计一个算法,通过遍历一趟链表,将链表中
//所有结点的链接方向逆转,并使first指针指向逆转后的第一个结点处(即原来的最后一个结点处),
//若原来链表空,则返回false.(说明:first指针是类SingleList的成员变量,是Node<T>为类的一个指针, Node类的定义为:
class Node {
T data;
Node<T> *link;
friend class SingleList<T>
};
//函数原型为:
template <class T>
bool SingleList<T>::Reverse( );

template <class T>
bool SingleList<T>::Reverse()
{
if(!first)return false;

Node<T> *p=first,*q;
first=NULL;
while(p){
q=p;
p->link=first;
first=p;
p=q;
}
return true;
}

手机上写的,将就看。设*head指向头节点,开节点指针*p,*p1,*temp; p=head; p1=p->next; while(p1!=NULL) {temp=p1->next; p1->next=p; p=p1; p1=temp;} head->next=NULL; head=p1;

链表逆转的算法应该很好想吧