输入一个链表,反转链表后,输出新链表的表头。
思路:链表反转用到了栈 进行操作,把一个链表先循环压进栈中,利用栈先进后出的特点,循环出栈就得到了反转后的链表。
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead == NULL || pHead -> next == NULL)
return pHead;
stack<ListNode *> s;
ListNode* p = pHead;
while(p -> next)
{
s.push(p);
p = p -> next;
}
ListNode* head = p;
while(!s.empty())
{
p -> next = s.top();
p = p -> next;
s.pop();
}
p -> next = NULL;
return head;
}
};