Чтобы эффективно перевернуть односвязный список в Java, вы можете использовать несколько методов. Вот несколько подходов:
Метод 1: итеративный подход
public ListNode reverseList(ListNode head) {
ListNode prev = null;
ListNode current = head;
ListNode next;
while (current != null) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return prev;
}
Метод 2: рекурсивный подход
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;
}
Метод 3: стековый подход
import java.util.Stack;
public ListNode reverseList(ListNode head) {
if (head == null || head.next == null) {
return head;
}
Stack<ListNode> stack = new Stack<>();
ListNode current = head;
while (current != null) {
stack.push(current);
current = current.next;
}
ListNode reversedList = stack.pop();
current = reversedList;
while (!stack.isEmpty()) {
current.next = stack.pop();
current = current.next;
}
current.next = null;
return reversedList;
}
Эти методы предоставляют различные способы инвертирования односвязного списка в Java. Вы можете выбрать тот, который лучше всего соответствует вашим требованиям.