在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; // 移动prevcurr = 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;}
}