0206. 反转链表
题目地址(206. 反转链表)
题目描述
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?
前置知识
公司
思路
关键点解析
代码
拓展
相关题目

最后更新于
这有帮助吗?
示例:
输入: 1->2->3->4->5->NULL
输出: 5->4->3->2->1->NULL
进阶:
你可以迭代或递归地反转链表。你能否用两种方法解决这道题?

最后更新于
这有帮助吗?
这有帮助吗?
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
if (!head || !head.next) return head;
let cur = head;
let pre = null;
while (cur) {
const next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
};/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* cur = head;
ListNode* next = NULL;
while (cur != NULL) {
next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}
};# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head: return None
prev = None
cur = head
while cur:
cur.next, prev, cur = prev, cur, cur.next
return prev/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
class Solution {
public ListNode reverseList(ListNode head) {
ListNode pre = null, cur = head;
while (cur != null) {
ListNode next = cur.next;
cur.next = pre;
pre = cur;
cur = next;
}
return pre;
}
}// 普通递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* tail = nullptr;
return reverseRecursive(head, tail);
}
ListNode* reverseRecursive(ListNode *head, ListNode *&tail) {
if (head == nullptr) {
tail = nullptr;
return head;
}
if (head->next == nullptr) {
tail = head;
return head;
}
auto h = reverseRecursive(head->next, tail);
if (tail != nullptr) {
tail->next = head;
tail = head;
head->next = nullptr;
}
return h;
}
};
// (类似)尾递归
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (head == nullptr) return head;
return reverseRecursive(nullptr, head, head->next);
}
ListNode* reverseRecursive(ListNode *prev, ListNode *head, ListNode *next)
{
if (next == nullptr) return head;
auto n = next->next;
next->next = head;
head->next = prev;
return reverseRecursive(head, next, n);
}
};var reverseList = function (head) {
// 递归结束条件
if (head === null || head.next === null) {
return head;
}
// 递归反转 子链表
let newReverseList = reverseList(head.next);
// 获取原来链表的第 2 个节点 newReverseListTail
let newReverseListTail = head.next;
// 调整原来头结点和第 2 个节点的指向
newReverseListTail.next = head;
head.next = null;
// 将调整后的链表返回
return newReverseList;
};class Solution:
def reverseList(self, head: ListNode) -> ListNode:
if not head or not head.next: return head
ans = self.reverseList(head.next)
head.next.next = head
head.next = None
return ans