1. 对应力扣题目连接
2. 实现案例代码
下面使用两种方式实现:
- 迭代方法-反转链表
- 递归方法-反转链表
public class ReverseLinkedList {
public static void main(String[] args) {
// 示例链表:[1, 2, 3, 4, 5]
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
// 反转链表
ListNode reverse = reverse(null, head);
printList(reverse); // 输出:[5, 4, 3, 2, 1]
}
public static void printList(ListNode head) {
ListNode current = head;
while (current != null) {
System.out.print(current.val + " ");
current = current.next;
}
System.out.println();
}
/**
* 迭代方法反转链表
* @param head
* @return
*/
public ListNode reverseListIterative(ListNode head) {
ListNode prev = null;
ListNode current = head;
while (current != null) {
ListNode next = current.next; // 保存下一个节点
current.next = prev; // 反转当前节点的指针
prev = current; // 移动前指针到当前节点
current = next; // 移动当前节点到下一个节点
}
return prev; // 新的头节点
}
/**
* 递归方法反转链表-1
* @param head
* @return
*/
public ListNode reverseListRecursive(ListNode head) {
if (head == null || head.next == null) {
return head; // 基本情况:空链表或只有一个节点的链表
}
ListNode newHead = reverseListRecursive(head.next); // 反转后续链表
head.next.next = head; // 将后续节点指向当前节点
head.next = null; // 当前节点的next置为null
return newHead; // 返回新的头节点
}
/**
* 递归方法反转链表-2
* @param prev
* @param cur
* @return
*/
private static ListNode reverse(ListNode prev, ListNode cur) {
if (cur == null) {
return prev;
}
ListNode temp = cur.next;// 先保存下一个节点
cur.next = prev;// 反转
// 更新prev、cur位置
// prev = cur;
// cur = temp;
return reverse(cur, temp);
}
}
/**
* 节点类
*/
class ListNode {
int val;
ListNode next;
ListNode() {
}
ListNode(int val) {
this.val = val;
}
ListNode(int val, ListNode next) {
this.val = val;
this.next = next;
}
}