206. Reverse Linked List*
原创
©著作权归作者所有:来自51CTO博客作者珍妮的选择的原创作品,请联系作者获取转载授权,否则将追究法律责任
206. Reverse Linked List*
https://leetcode.com/problems/reverse-linked-list/
题目描述
Reverse a singly linked list.
Example:
Input: 1->2->3->4->5->NULL
Output: 5->4->3->2->1->NULL
Follow up:
A linked list can be reversed either iteratively or recursively. Could you implement both?
C++ 实现 1
翻转链表是非常经典的题, 迭代的方法需要铭记于心.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head) return nullptr;
ListNode *prev = nullptr;
while (head) {
auto tmp = head->next;
head->next = prev;
prev = head;
head = tmp;
}
return prev;
}
};
C++ 实现 2
递归的方法.
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
auto tmp = head->next;
auto new_head = reverseList(head->next);
tmp->next = head;
head->next = nullptr;
return new_head;
}
};