解题思路:
(1)先保存再遍历
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead) return pHead;
vector<ListNode*> v;
while(pHead){
v.push_back(pHead);
pHead=pHead->next;
}
for(int i=v.size()-1;i>=1;i--) {
v[i]->next=v[i-1];
}
v[0]->next=nullptr;
return v[v.size()-1];
}
};
(2)直接遍历赋值
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead) return pHead;
ListNode *pre=nullptr,*cur=pHead,*next=nullptr;
while(cur) {
next=cur->next;
cur->next=pre;
pre=cur;
cur=next;
}
return pre;
}
};