首页 > 其他 > 详细

题目:206. 反转链表

时间:2021-04-05 12:30:29      阅读:27      评论:0      收藏:0      [点我收藏+]

题目: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;
    }

题目:206. 反转链表

原文:https://www.cnblogs.com/init-qiancheng/p/14617908.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!