题目描述
输入一个链表,反转链表后,输出新链表的表头。
基本思路
把链表里的节点先压栈,然后弹栈。
代码实现
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* ReverseList(ListNode* pHead) {
ListNode *p = pHead;
if (p==NULL || p->next==NULL) { return pHead; }
else {
stack<ListNode*> stk;
while (p != NULL) {
stk.push(p);
p = p->next;
}
ListNode* Head = stk.top();
stk.pop();
p = Head;
while (!stk.empty()) {
p->next = stk.top();
p = p->next;
stk.pop();
}
p->next = NULL;
return Head;
}
}
};