二分查找你学废了吗?快来看看这道题如何使用二分查找解决吧!
LeetCode链接:206. 反转链表
1.题目描述
给你单链表的头节点 head
,请你反转链表,并返回反转后的链表。
示例 1:

1 2
| 输入:head = [1,2,3,4,5] 输出:[5,4,3,2,1]
|
示例 2:

示例 3:
提示:
- 链表中节点的数目范围是
[0, 5000]
-5000 <= Node.val <= 5000
进阶:链表可以选用迭代或递归方式完成反转。你能否用两种方法解决这道题?
2.题解
2.1 双指针(迭代法)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| class Solution { public ListNode reverseList(ListNode head) { ListNode pre = null; ListNode cur = head; while (cur != null) { ListNode temp = cur.next; cur.next = pre; pre = cur; cur = temp; } return pre; } }
|
2.2 递归法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Solution { public ListNode reverseList(ListNode head) { return reverse(null, head); }
public ListNode reverse(ListNode pre, ListNode cur) { if (cur == null) return pre;
ListNode next = cur.next; cur.next = pre;
return reverse(cur, next); } }
|