[导读]C++实现单链表逆序的技巧。
struct list_node
{
list_node(int a,list_node* b):data(a),next(b) //这个为了测试方便
{}
int data;
list_node* next;
};
void reserve(list_node* phead)
{
list_node* p = phead->next;
if(p == NULL || p->next == NULL) return; //只有头节点或一个节点
list_node* p1=p->next;
p->next=NULL;
while(p1!=NULL)
{
p = p1->next;
p1->next = phead->next;
phead->next = p1;
p1 = p;
}
}
测试程序:
list lt;
lt.phead = new list_node(0,0);
lt.phead->next = new list_node(1,0);
lt.phead->next->next = new list_node(2,0);
lt.phead->next->next->next = new list_node(3,0);
lt.reserve();
list_node * p = lt.phead;
while(p)
{
coutnext;
}
原文出自【比特网】,转载请保留原文链接:http://soft.chinabyte.com/database/470/11398470.shtml