反转链表的思路:用一个栈,先按照链表的正序压栈,然后链表为空时 记录此时栈顶元素就是 新链表的头结点,再依次出栈,改变结点的指向,指向栈顶。直到栈空。返回新链表。
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
#include <stack>
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
if(pHead==NULL)
return NULL;
stack<ListNode *>s;
while(pHead!=NULL)
{
s.push(pHead);
pHead=pHead->next;
}
ListNode *newHead=s.top();
ListNode *p=newHead;
s.pop();
while(!s.empty())
{
p->next=s.top();
s.pop();
p=p->next;
}
p->next=NULL;
return newHead;
}
};