Brushing notes (ten)-reverse list
Title description
Enter a linked list, and after reversing the linked list, output the header of the new linked list.
Idea: Use the stack, traverse from scratch to put the value on the stack, and then traverse from the stack to assign the value to the node.
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
stack<int> s;
ListNode* p=pHead;
while(p!=NULL)
{
s.push(p->val);
p=p->next;
}
ListNode* q=pHead;
while(q!=NULL)
{
q->val=s.top();
s.pop();
q=q->next;
}
return pHead;
}
};
I saw a code in the comment area, which was very good.