描述
给定一个单链表的头结点pHead,长度为n,反转该链表后,返回新链表的表头。
数据范围: n\leq1000n≤1000
要求:空间复杂度 O(1) ,时间复杂度 O(n) 。
如当输入链表{1,2,3}时,
经反转后,原链表变为{3,2,1},所以对应的输出为{3,2,1}。
方案一:利用 vector 存储 空间复杂度O(n),不符合题目要求
//ListNode 定义
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode *pHead) {
if(!pHead) return nullptr;
vector<ListNode*> v;
while(pHead){
v.push_back(pHead); //push_back 将元素放在 vector 的最后一位的下一位
pHead = pHead -> next ;
}
reverse(v.begin(), v.end()); //反转函数
ListNode *head = v[0]; //新链表的头
ListNode *cur = head; //工作指针
for(int i=1; i<v.size() ;++i){
cur ->next = v[i];
cur = cur->next;
}
cur->next = nullptr; //尾部置为 nullptr
return head;
}
};
采用指针直接更改链表 空间复杂度 O(1)
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution{
public:ListNode* ReverseList(ListNode *pHead){
ListNode* p = nullptr; //新链表的头
ListNode* q = nullptr; //工作指针
while(pHead){
q = pHead ->next;
pHead ->next = p;
p = pHead ;
pHead = q ;
}
return p ;
}
};