在Java中,可以使用迭代和递归两种方法来反转链表。
- 迭代法:
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode curr = head;
while (curr != null) {
ListNode nextTemp = curr.next;
curr.next = prev;
prev = curr;
curr = nextTemp;
}
return prev;
}
- 递归法:
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
ListNode reversedList = reverseList(head.next);
head.next.next = head;
head.next = null;
return reversedList;
}
这两种方法都能有效地反转一个链表,具体选择哪种取决于个人偏好和实际的使用场景。