题目描述

反转单向链表

解题思路

很简单面试很常问的题目。解法有两种,递归法和头插法。

递归法:先将头结点反转,头结点的next指向null,再将头结点的下一个节点链表反转,最后头结点的下一个节点指向头结点。

public ListNode reverseList(ListNode head) {
    if (head == null || head.next == null) {
        return head;
    }
    ListNode next = head.next;
    head.next = null;
    ListNode res = reverseList(next);
    next.next = head;
    return res;
}

头插法:构造一个虚拟的头结点,将链表的每一个节点插入到dummy节点的next节点,最后返回dummy.next。

public ListNode reverseList(ListNode head) {
    ListNode dummy = new ListNode(-1);
    while (head != null) {
        ListNode next = head.next;
        head.next = dummy.next;
        dummy.next = head;
        head = next;
    }
    return dummy.next;
}

相关文章:

  • 2021-07-21
  • 2021-09-01
  • 2022-12-23
  • 2022-12-23
  • 2021-07-02
  • 2021-11-14
猜你喜欢
  • 2021-11-03
  • 2021-10-12
  • 2021-10-23
  • 2021-10-30
  • 2021-06-13
  • 2022-02-08
  • 2021-06-28
相关资源
相似解决方案