【剑指Offer】24. 反转链表

2020-12-07 09:59:06 浏览数 (1)

NowCoder

解题思路

递归

代码语言:javascript复制
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        
        ListNode next = head.next;
        head.next = null;
        
        ListNode newHead = ReverseList(next);
        
        next.next = head;
        
        return newHead;
    }
}

迭代

使用头插法。

代码语言:javascript复制
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        ListNode newHead = new ListNode(-1);
        
        while(head != null) {
            ListNode next = head.next;
            head.next = newHead.next;
            newHead.next = head;
            
            head = next;
        }
        
        return newHead.next;
    }
}

0 人点赞