《LeetCode力扣练习》代码随想录——链表(反转链表—Java)
刷题思路来源于 代码随想录
206. 反转链表
-
双指针法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { if(head==null){ return null; } ListNode slow=null; ListNode fast=head; while(fast!=null){ ListNode temp=fast.next; fast.next=slow; slow=fast; fast=temp; } return slow; } } -
递归法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode reverseList(ListNode head) { if(head==null){ return null; } return reverse(null,head); } public ListNode reverse(ListNode slow,ListNode fast){ if(fast==null){ return slow; } ListNode temp=fast.next; fast.next=slow; return reverse(fast,temp); } }
本文介绍了在LeetCode中使用Java实现的反转链表问题,分别展示了双指针法和递归法的解决方案,详细阐述了两种算法的逻辑和步骤。
1580

被折叠的 条评论
为什么被折叠?



