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

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

#### Topic description

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 {
/**
* 反转结点
*
* @return
*/
public static ListNode reverseList(ListNode head) {
// 如果链表为空或者只有一个节点，不需要反转，直接返回原链表
}

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

/**
* 递归法
*
* @return
*/
public static ListNode reverseList2(ListNode head) {
// 递归的终止条件
}

// 递归处理
return reverse;
}

public static void main(String[] args) {
// 测试用例

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

System.out.println("反转之后");

System.out.println("再次反转之后");