链表# 发布于2021-02-02 上次编辑2021-04-20 单链表# C++ 1 2 3 4 5 6 7struct ListNode { int val; ListNode *next; ListNode() : val(0), next(nullptr) {} ListNode(int x) : val(x), next(nullptr) {} ListNode(int x, ListNode *next) : val(x), next(next) {} }; Python 1 2 3 4class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next 构建链表# 头插法:构建的链表的元素与输入的元素方向相反。 尾插法:构建的链表的元素与输入的元素方向相同。 反转链表# 迭代 Python 1 2 3 4 5 6 7 8 9 10 11class Solution: def reverseList(self, head: ListNode) -> ListNode: prev, cur = None, head while cur: nxt = cur.next cur.next = prev prev = cur cur = nxt return prev C++ 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15class Solution { public: ListNode* reverseList(ListNode* head) { ListNode *prev = nullptr, *cur = head; while (cur) { auto next = cur->next; cur->next = prev; prev = cur; cur = next; } return prev; } }; 递归 Python 1 2 3 4 5 6 7 8 9 10 11class Solution: def reverseList(self, head: ListNode) -> ListNode: if not head or not head.next: return head rhs = self.reverseList(head.next) head.next.next = head head.next = None return rhs C++ 1 2 3 4 5 6 7 8 9 10 11 12 13class Solution { public: ListNode* reverseList(ListNode* head) { if (!head || !head->next) return head; auto rhs = reverseList(head->next); head->next->next = head; head->next = nullptr; return rhs; } }; 例题# 206. 反转链表 92. 反转链表 II 返回顶部 在手机上阅读