diff --git a/problems/0206.翻转链表.md b/problems/0206.翻转链表.md index b465cdf9..e132fb0d 100644 --- a/problems/0206.翻转链表.md +++ b/problems/0206.翻转链表.md @@ -102,7 +102,47 @@ public: Java: +```java +class Solution { + // 双指针 + public ListNode reverseList(ListNode head) { + ListNode prev = null; + ListNode cur = head; + ListNode temp = null; + while (cur != null) { + temp = cur.next;// 保存下一个节点 + cur.next = prev; + prev = cur; + cur = temp; + } + return prev; + } +} +``` +```java +class Solution { + /** + * 递归 + */ + public ListNode reverseList(ListNode head) { + return reverse(null, head); + } + + private ListNode reverse(ListNode prev, ListNode cur) { + if (cur == null) { + return prev; + } + ListNode temp = null; + temp = cur.next;// 先保存下一个节点 + cur.next = prev;// 反转 + // 更新prev、cur位置 + prev = cur; + cur = temp; + return reverse(prev, cur); + } +} +``` Python: