class: fix LinkedList.offer method adding item incorrectly at the beginning

Fix #772
This commit is contained in:
Ludovic Dubost 2023-10-01 19:38:34 +02:00 committed by Alexey Andreev
parent 0b2d1428fb
commit 4a81615749
2 changed files with 21 additions and 12 deletions

View File

@ -95,17 +95,7 @@ public class TLinkedList<E> extends TAbstractSequentialList<E> implements TDeque
@Override @Override
public boolean offer(E e) { public boolean offer(E e) {
Entry<E> entry = new Entry<>(); addLast(e);
entry.item = e;
entry.next = firstEntry;
if (firstEntry != null) {
firstEntry.previous = entry;
} else {
lastEntry = entry;
}
firstEntry = entry;
++modCount;
++size;
return true; return true;
} }
@ -149,7 +139,17 @@ public class TLinkedList<E> extends TAbstractSequentialList<E> implements TDeque
@Override @Override
public void addFirst(E e) { public void addFirst(E e) {
offer(e); Entry<E> entry = new Entry<>();
entry.item = e;
entry.next = firstEntry;
if (firstEntry != null) {
firstEntry.previous = entry;
} else {
lastEntry = entry;
}
firstEntry = entry;
++modCount;
++size;
} }
@Override @Override

View File

@ -308,4 +308,13 @@ public class LinkedListTest {
lit.add("x"); lit.add("x");
assertEquals(List.of("d", "x", "a"), list); assertEquals(List.of("d", "x", "a"), list);
} }
@Test
public void offerOrder() {
var list = new LinkedList<String>();
list.offer("1");
list.offer("2");
assertEquals("1", list.getFirst());
assertEquals("2", list.getLast());
}
} }