Разворот односвязного списка
Написал метод разворота односвязного списка. Метод работает неверно, выдавая только одно значение не в правильном порядке. Подскажите где ошибка?
public void reverse(){
Node currNode = head;
Node prevNode = null;
while (currNode != null){
Node next = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = next;
}
}
Ответы (2 шт):
Автор решения: tym32167
→ Ссылка
ОБновите ваш head как то так
public void reverse(){
Node currNode = head;
Node prevNode = null;
while (currNode != null){
Node next = currNode.next;
currNode.next = prevNode;
prevNode = currNode;
currNode = next;
}
head = prevNode;
}
Автор решения: Aidar Nigmatullin
→ Ссылка
interface ILinkedListNode<T> {
value: T;
next: ILinkedListNode<T> | null;
hasNext: boolean
}
class LinkedListNode<T> implements ILinkedListNode<T> {
value: T;
next: ILinkedListNode<T> | null;
hasNext: boolean;
constructor(props: T, prev: ILinkedListNode<T> | null) {
this.value = props;
this.next = null
this.hasNext = false
if (prev) {
prev.next = this;
prev.hasNext = true
}
}
}
class LinkedList<T> implements ILinkedList<T> {
private _size: number = 0
private firstItem: ILinkedListNode<T> | null = null
private lastItem: ILinkedListNode<T> | null = null
constructor(props?: T | null) {
props && this.add(props)
}
add(value: T): void {
this._size++;
if (!this.firstItem) {
this.firstItem = new LinkedListNode(value, null)
this.lastItem = this.firstItem
} else {
const item = new LinkedListNode(value, this.lastItem);
this.lastItem = item;
}
}
public reverse(): ILinkedList<T> {
let [prev, middle, next] = [
this.firstItem, this.firstItem?.next, this.firstItem?.next?.next];
if (!prev) {
return new LinkedList<T>();
}
if (!middle) {
return new LinkedList<T>(prev.value);
}
if (!next) {
const linkedList = new LinkedList(middle.value);
linkedList.add(prev.value)
return linkedList
}
this.lastItem = prev;
this.lastItem.next = null;
this.lastItem.hasNext = false
for (; next;) {
middle.next = prev;
middle.hasNext = true;
prev = middle;
middle = next;
next = next.next
if (!next) {
this.firstItem = middle;
this.firstItem.next = prev;
this.firstItem.hasNext = true;
}
}
return this
}
}
// проверка
const arr = [1, 2, 3, 4, 5, 6, 7]
const linkedList = new LinkedList()
arr.forEach(el => {
linkedList.add(el)
})
linkedList.reverse();
linkedList.forEach(el => console.log('forEach in reverse', el))