链表逆置

本文介绍链表逆置的不同实现方式,包括非递归实现和两种递归实现方法(一种带返回值,另一种不带返回值)。通过具体的C++代码示例详细展示了每种方法的具体操作步骤。

同学提到了这个问题,自己动手编了一下。

有两种方法:递归和非递归。

递归中又有两种:带返回值的和不带返回值的。

代码如下:

/****    链表的逆置      *****/
/*
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;
}


评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值