题目:206. 反转链表

题目:206. 反转链表

反转一个单链表。

方式一(迭代)

 public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode curr = head;
        ListNode prev = null;
        while (curr != null) {
            ListNode temp = curr.next;
            curr.next = prev;
            prev = curr;
            curr = temp;
        }
        return prev;
    }

方式二(递归)

  public ListNode reverseList(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode res = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return res;
    }
posted @ 2021-04-05 10:38  迁承_0204  阅读(24)  评论(0编辑  收藏  举报