遍历链表,使用一个栈保存每一个节点,然后从尾结点开始依次出栈依次出栈。
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if (pHead==0)return 0;
stack<ListNode*>s;
while(pHead)
{
s.push(pHead);
pHead=pHead->next;
}
ListNode*head=s.top(),*h=head;
s.pop();
while(!s.empty())
{
head->next=s.top();
s.pop();
head=head->next;
}
head->next=0;
return h;
}
};
京公网安备 11010502036488号