1
头图

Niuke.com High Frequency Algorithm Question Series - BM1 Reverse Linked List

Topic description

Given a head node pHead of a singly linked list (the head node has a value), the length is n, after reversing the linked list, return the head of the new linked list.

See the original title: BM1 reverse linked list

Solution 1: Node inversion

  • First, if head is empty or has only one node, return directly.
  • Otherwise, use the first and next pointers to point to the first two nodes of the linked list respectively, and reverse their next pointer fields, and then continue to traverse the subsequent nodes of the linked list until the last node is reversed. Note that you need to point the next of the head node to null.
  • Finally, return the first node, which is the head node of the reversed new linked list.

Solution 2: Recursive method

  • Similarly, you first need to judge, if the head is empty or there is only one node, return directly.
  • Otherwise, it is processed recursively. The recursive processing flow is as follows:

    • The terminal condition of the recursion is that the head node is empty or there is no next node;
    • Otherwise, recursively get the reverse linked list of head.next as reverse, and then point the next pointer of the reverse to head, and also remember to point the next of the head node to null.
 public class Bm001 {
    /**
     * 反转结点
     *
     * @param head 原链表的头结点
     * @return
     */
    public static ListNode reverseList(ListNode head) {
        // 如果链表为空或者只有一个节点,不需要反转,直接返回原链表
        if (head == null || head.next == null) {
            return head;
        }

        ListNode first = head, second = head.next;
        first.next = null;
        while (first != null && second != null) {
            ListNode temp = first;
            first = second;
            second = second.next;
            first.next = temp;
        }
        return first;
    }

    /**
     * 递归法
     *
     * @param head 原链表的头结点
     * @return
     */
    public static ListNode reverseList2(ListNode head) {
        // 递归的终止条件
        if (head == null || head.next == null) {
            return head;
        }

        // 递归处理
        ListNode reverse = reverseList2(head.next);
        head.next.next = head;
        head.next = null;
        return reverse;
    }

    public static void main(String[] args) {
        // 测试用例
        ListNode head = ListNode.testCase1();

        System.out.println("反转之前");
        ListNode.print(head);

        System.out.println("反转之后");
        ListNode newHead = reverseList(head);
        ListNode.print(newHead);

        System.out.println("再次反转之后");
        ListNode newHead2 = reverseList2(newHead);
        ListNode.print(newHead2);
    }
}
$1.01^{365} ≈ 37.7834343329$
$0.99^{365} ≈ 0.02551796445$
Believe in the power of persistence!

醉舞经阁
1.8k 声望7.1k 粉丝

玉树临风,仙姿佚貌!