在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;
}
這兩種方法都能有效地反轉一個鏈表,具體選擇哪種取決于個人偏好和實際的使用場景。