206. 反转链表

迭代

public class Algorithm {

    public static void main(String[] args) {

        int[] arr = {1, 2, 6, 3, 4, 5, 6};
        ListNode head = new ListNode(arr);

        System.out.println(head);
        System.out.println(new Solution().reverseList(head));
    }
}

class Solution {
    public ListNode reverseList(ListNode head) {

        ListNode prev = null;
        ListNode curr = head;

        while (curr != null) {

            /**
             * 因为空指针不能进行链表操作,因此在cur不为空时才能指向其下一个节点
             */
            ListNode tem = curr.next;
            curr.next = prev;
            prev = curr;
            curr = tem;
        }

        return prev;
    }
}

class ListNode{

    int val;
    ListNode next;
    ListNode() {}

    ListNode(int val) {

        this.val = val;

    }

    ListNode(int val, ListNode next) {

        this.val = val; this.next = next;
    }

    ListNode(int[] arr){

        if (arr == null || arr.length == 0){
            throw new IllegalArgumentException("数组是空的");
        }

        this.val = arr[0];
        ListNode prev = this;

        for (int i = 1; i < arr.length; i++) {

            prev.next = new ListNode(arr[i]);
            prev = prev.next;
        }
    }

    @Override
    public String toString(){

        StringBuilder str = new StringBuilder();

        ListNode curr = this;
        while (curr != null){
            str.append(curr.val + "——>");
            curr = curr.next;
        }
        str.append("null");

        return str.toString();
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(1)
 */

递归

class Solution {
    public ListNode reverseList(ListNode head) {

        /**
         * 边界条件
         * 如果链表为空或者只有一个节点,那根本不需要反转
         * head.next == null这个条件很重要,也容易漏掉
         */
        if (head == null || head.next == null){
            return head;
        }

        ListNode newHead = reverseList(head.next);

        /**
         * 但凡涉及到curr.next操作,都要考虑curr是否可能为空,否则肯定抛出空指针异常
         * 如果不考虑head.next == null这个情况,那么head.next.next等价于null.next,肯定报错
         */
        head.next.next = head;
        head.next = null;

        return newHead;
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/reverse-linked-list/

posted @ 2021-10-18 13:36  振袖秋枫问红叶  阅读(30)  评论(0)    收藏  举报