在Java中实现单链表的逆序,可以通过迭代或递归两种方式。以下是两种方法的详细实现:
1. 迭代方法(推荐)
public class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}
class Solution {
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next; // 保存下一个节点
curr.next = prev; // 反转指针
prev = curr; // 移动prev
curr = nextTemp; // 移动curr
}
return prev; // prev现在是新的头节点
}
}
2. 递归方法
class Solution {
public ListNode reverseList(ListNode head) {
// 递归终止条件
if (head == null || head.next == null) {
return head;
}
ListNode newHead = reverseList(head.next); // 递归反转后续链表
head.next.next = head; // 将当前节点设置为后续节点的下一个节点
head.next = null; // 断开原有连接
return newHead;
}
}
788

被折叠的 条评论
为什么被折叠?



