描述
翻转一个链表
样例
给出一个链表1->2->3->null,这个翻转后的链表为3->2->1->null
思考
- 第一眼看到我是拒绝的,单链表又没有前指针,怎么同时 swap 交换值
- 后来一想,好像也没有要求交换值,赋值效果也是等同的,又是翻转,第一感觉想到栈
代码
// By Lentitude
/**
* Definition of ListNode
*
* class ListNode {
* public:
* int val;
* ListNode *next;
*
* ListNode(int val) {
* this->val = val;
* this->next = NULL;
* }
* }
*/
class Solution {
public:
/**
* @param head: The first node of linked list.
* @return: The new head of reversed linked list.
*/
ListNode *reverse(ListNode *head) {
// write your code here
if (head == NULL) return NULL;
stack<int> stack;
ListNode *pre = head;
while (pre != NULL){
// 用栈顺序保存结果
stack.push(pre->val);
pre = pre->next;
}
pre = head;
while (pre != NULL){
// 栈逆序赋值
pre->val = stack.top();
stack.pop();
pre = pre->next;
}
return head;
}
};