Reverse a singly linked list.
思路:
。。。
解:
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(!head || !head->next)
return head;
std::vector<ListNode*> list;
ListNode* stepNode = head;
while(stepNode)
{
list.push_back(stepNode);
stepNode = stepNode->next;
}
ListNode* resultNode = list[list.size() - 1];
stepNode = resultNode;
for(size_t idx = list.size() - 1; idx > 0; idx--)
{
stepNode->next = list[idx - 1];
stepNode = stepNode->next;
}
stepNode->next = nullptr;
return resultNode;
}
};