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

翻转链表是非常经典的题, 迭代的方法需要铭记于心.


206. Reverse Linked List*_链表

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

递归的方法.


206. Reverse Linked List*_链表_02

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;
}
};