15. 反转链表

2019-03-13  本文已影响0人  丶沧月

解题思路

递归

public ListNode ReverseList(ListNode head) {
        //递归终止条件:找到链表最后一个结点
        if (head == null || head.next == null) {
            return head;
        }
        //先反转后面的链表
        ListNode newHead = ReverseList(head.next);
        //将后一个链表结点指向前一个结点
        head.next.next = head;
        //将原链表中前一个结点指向后一个结点的指向关系断开
        head.next = null;
        return newHead;
    }

迭代

    public ListNode ReverseList(ListNode head) {
        ListNode newList = new ListNode(-1);
        while (head != null) {
            ListNode next = head.next;
            head.next = newList.next;
            newList.next = head;
            head = next;
        }
        return newList.next;
    }
上一篇 下一篇

猜你喜欢

热点阅读