题目
输入一个长度为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;
}