- 题目如字面意思
方法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 == nullptr){
return nullptr;
}
if(pHead->next == nullptr){
return pHead;
}
ListNode* h = nullptr;
ListNode* pHeadNext = nullptr;
while(pHead){
pHeadNext = pHead->next;
pHead->next = h;
h = pHead;
pHead = pHeadNext;
}
return h;
}
};