LeetCode206-逆转链表-简单-Java实现

    技术2025-10-06  9

    搞混了头结点和第一个节点,要仔细读题哦~

    /** * 用头插法 反转链表 * 注意这里不要管头结点 * @param head * @return */ public ListNode reverseList (ListNode head) { if (head == null || head.next == null) return head; ListNode node = null; // 反转后新链表 /* * 创建一个临时节点,存储原链表现在的节点 * 修改当前节点指针域,当前节点指向反转后的链表 * 更新反转后的链表 * 原链表指向下一个节点 */ while (head != null) { ListNode next = head.next; // 备份原链表下一个节点 head.next = node; // cur 指向 node node = head; // node永远都是第一个节点 head = next; // 原链表 cur指向下一个节点 } return node; }

    原来错误的代码: 为什么测试不通过啊

    public ListNode reverseList (ListNode head) { if (head == null || head.next == null) return null; ListNode cur = head.next; // 就是这里错了!! ListNode node = null; // 反转后新链表 while (cur != null) { ListNode next = cur.next; // 备份原链表下一个节点 cur.next = node; // cur 指向 node node = cur; // node永远都是第一个节点 cur = next; // 原链表 cur指向下一个节点 } head.next = node; // 将原链表的头结点指向反转后的链表 return node; }

    测试用例显示: 考虑头结点的话:

    /** * 用头插法 反转链表 * 新链表的头结点 * 这个链表类中,不能有参数,因为测试类中是直接生成表的不是节点 * @param head * @return */ public Node<E> reverseList () { if (head == null || head.next == null) return null; Node<E> cur = head.next; // 原链表 cur指向第一个节点 Node<E> node = null; // 反转后新链表 /* * 创建一个临时节点,存储原链表现在的节点 * 修改当前节点指针域,当前节点指向反转后的链表 * 更新反转后的链表 * 原链表指向下一个节点 */ while (cur != null) { Node<E> next = cur.next; // 备份原链表下一个节点 cur.next = node; // cur 指向 node node = cur; // node永远都是第一个节点 cur = next; // 原链表 cur指向下一个节点 } head.next = node; // 将原链表的头结点指向反转后的链表 return node; }
    Processed: 0.010, SQL: 9