问题
思路
两种办法,头插法或者就地置逆。
代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(!pHead)
return NULL;
ListNode* pre = NULL; // 一定要初始化为空
while(pHead){
ListNode* pNext = pHead->next;
pHead->next = pre;
pre = pHead;
pHead = pNext;
}
ListNode* head = pre;
while( head ){ std::cout << head->val; head=head->next; }
return pre;
}
};