同学提到了这个问题,自己动手编了一下。
有两种方法:递归和非递归。
递归中又有两种:带返回值的和不带返回值的。
代码如下:
/**** 链表的逆置 *****/
/*
struct node {
int a;
node* next;
node(): a(0), next(NULL) {}
};
void Creat_list(node* &head, int n)
{
node* p = new node;
p->a = n;
if(!head)
head->next = p;
else {
p->next = head->next;
head->next = p;
}
}
void show(node* &head)
{
node* p = head->next;
while(p) {
cout << p->a << " ";
p = p->next;
}
cout << endl;
}
//*** 非递归实现
void reverse(node* &head) //带头结点的链表反转
{
node* pre = head->next;
node* cur = pre->next;
node* nex = NULL;
if(!pre || !cur)
return;
while(cur) {
nex = cur->next;
cur->next = pre;
pre = cur;
cur = nex;
}
head->next->next = NULL;
head->next = pre;
}
//递归实现(带返回值)
node* reverse(node* &head, node* cur)
{
if(!cur || !cur->next) {
head->next = cur;
return cur;
}
else {
node* tmp = reverse(head, cur->next);
tmp->next = cur;
cur->next = NULL;
return cur;
}
}
// 递归实现( 不 带返回值)
void reverse1(node* &head, node* cur)
{
if(!cur || !cur->next) {
head->next = cur;
}
else {
reverse(head, cur->next);
cur->next->next = cur;
cur->next = NULL;
}
}
int main()
{
node* head = new node;
Creat_list(head, 1);
Creat_list(head, 2);
Creat_list(head, 3);
Creat_list(head, 4);
Creat_list(head, 5);
Creat_list(head, 6);
show(head);
cout << endl;
// reverse(head); //非递归
node* p = head->next;
// node* a = reverse(head, p); // 递归带返回值 (其实不用带返回值,带返回值的较复杂)
reverse1(head, p);
show(head);
getchar();
return 0;
}
本文介绍链表逆置的不同实现方式,包括非递归实现和两种递归实现方法(一种带返回值,另一种不带返回值)。通过具体的C++代码示例详细展示了每种方法的具体操作步骤。
1037

被折叠的 条评论
为什么被折叠?



