JZ24 反转链表[C++]

题目

输入一个长度为n链表,反转链表后,输出新链表的表头。

数据范围: n\leq1000n≤1000

要求:空间复杂度 O(1),时间复杂度 O(n)。

如当输入链表{1,2,3}时,

经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。

以上转换过程如下图所示:

示例1

输入:

{1,2,3}
返回值:
{3,2,1}

示例2

输入:

{}

返回值:

{}

说明:

空链表则输出空           

代码

#include<iostream>
using namespace std;

struct Node
{
	int data;
	Node* next;
};

Node* Create(int n)
{
	Node* p, * h, * s;
	h = new Node;
	h->next = NULL;
	p = h;
	for (int i = 0; i < n; i++)
	{
		s = new Node;
		cin >> s->data;
		p->next = s;
		p = s;
	}
	p->next = NULL;
	return h;
}

void Print(Node* h)
{
	Node* p = h;
	while (p != NULL)
	{
		cout << p->data << "\t";
		p = p->next;
	}
	cout << endl;
}
Node* reverse(Node* h)
{
	Node* pre = NULL;
	Node* cur = h->next;
	Node* nex = NULL;
	while (cur != NULL)
	{
		nex = cur->next;
		cur->next = pre;
		pre = cur;
		cur = nex;
	}
	return pre;
}

int main()
{
	Node* head1 = new Node;
	head1->next = NULL;
	Node* head2 = new Node;
	head2->next = NULL;
	int i;
	cout << "请输入单链表的结点个数:";
	cin >> i;
	cout << "请输入反转之前的单链表结点:";
	head1 = Create(i);
	cout << "经过反转之后的结点为:";
	head2 = reverse(head1);
	Print(head2);
	return 0;
}

知识点

1.反转链表其实本质就是改变链表的指向再将反转后的链表打印输出

Node* pre = NULL;
	Node* cur = h->next;
	Node* nex = NULL;
	while (cur != NULL)
	{
		nex = cur->next;
		cur->next = pre;
		pre = cur;
		cur = nex;
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值