题目
分析
全部存入栈里再构造一条新链表。
题解
/**
* 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) {
stack<int> ans;
if(head == NULL)
return NULL;
while(head != NULL){
ans.push(head->val);
head = head->next;
}
ListNode newhead(0);
ListNode *p = &newhead;
ListNode *q = &newhead;
while(ans.size() != 0){
int value = ans.top();
ans.pop();
ListNode *temp = new ListNode(value);
p->next = temp;
p = p->next;
}
q = q->next;
return q;
}
};