c++链表反转代码

#include<iostream>
using namespace std;
typedef struct node {    //使用typedef,可用再后面定义新的结构体名,不然就只能用node
	/*string name;
	int age;*/
	int val;
	node* next;
}L;

L* create(int n)
{
	L* head = nullptr;
	L* pre = nullptr;
	for (int i = 1; i <= n; i++)
	{
		L* cur = new L;
		cur->val = i;
		cur->next = nullptr;
		if (head == nullptr)
		{
			head = cur;
			pre = cur;
		}
		else {
			
			pre->next = cur;
			pre = cur;
		}
	}
	return head;
}

L* reset(L* head) {
	L* pre = nullptr;
	L* cur = nullptr;
	while (head)
	{
		cur = head->next;   //把第一个节点里保存的第二个节点的地址保存到cur中
		head->next = pre;   //把pre的地址保存到第一个节点中,又因为head和pre会指向同一个地方,        
                            //所以后面的循环中head->next内保存的是上一个节点的地址
		pre = head;
		head = cur;
	}
	return pre;
}

void printlist(L* head) {
	while (head)
	{
		cout << head->val;
		head = head->next;
		if (head)
			cout << "->";
	}
	cout << endl;
}

int main()
{	
	L* head = create(10);
	printlist(head);
	head = reset(head);
	printlist(head);
	return 0;
}

自学写的,可用运行。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

北木ww

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值