单链表反转:Python/Java/C++三解

📅 2026/7/1 2:14:39
单链表反转:Python/Java/C++三解
LeetCode206给你单链表的头节点head请你反转链表并返回反转后的链表。示例一输入head [1,2,3,4,5]输出[5,4,3,2,1]Python解法1.数组翻转class Solution: def reverseList(self, head: Optional[ListNode]) - Optional[ListNode]: if not head: return None temp [] while head: temp.append(head.val) head head.next dummy ListNode() p dummy for num in reversed(temp): p.next ListNode(num) p p.next return dummy.next2.迭代原地翻转class Solution: def reverseList(self, head: Optional[ListNode]) - Optional[ListNode]: pre None cur head while cur: # 先保存下一个节点防止断链 nxt cur.next # 翻转当前节点指向 cur.next pre # 双指针后移 pre cur cur nxt # pre最后是新头节点 return pre3.递归class Solution: def reverseList(self, head: Optional[ListNode]) - Optional[ListNode]: # 终止条件空节点/最后一个节点 if not head or not head.next: return head # 递归拿到后半段反转后的头 new_head self.reverseList(head.next) # 翻转当前节点与后节点的指针 head.next.next head head.next None return new_headJava解法只展示后两种1.迭代class Solution { public ListNode reverseList(ListNode head) { ListNode pre null; ListNode cur head; while (cur ! null) { ListNode nxt cur.next; // 暂存下一个 cur.next pre; // 反转指向 pre cur; // pre后移 cur nxt; // cur后移 } return pre; } }2.递归class Solution { public ListNode reverseList(ListNode head) { // 终止空 / 最后一个节点 if (head null || head.next null) { return head; } ListNode newHead reverseList(head.next); head.next.next head; // 后节点指向自己 head.next null; // 切断原正向指针 return newHead; } }C解法1.迭代class Solution { public: ListNode* reverseList(ListNode* head) { ListNode* pre nullptr; ListNode* cur head; while (cur) { ListNode* nxt cur-next; cur-next pre; pre cur; cur nxt; } return pre; } };2.递归class Solution { public: ListNode* reverseList(ListNode* head) { if (!head || !head-next) { return head; } ListNode* newHead reverseList(head-next); head-next-next head; head-next nullptr; return newHead; } };