《LeetCode力扣练习》代码随想录——链表(反转链表---Java)

《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,leetcode,链表,java)