if I maintain a reference of the least added item
but not maintain a reference of most recently added
item, then I will have constant time "dequeue"
and linear time "enqueue"
. so this is my program which implement queue in java linked list. I want to ask if this program maintains both least added item and most recently added item? so it's all constant time when I "dequeue"
or "enqueue"
? thank you!
add: I kinda agree with what first answer said, so I tried the debugging mode and it shows that the oldlast hasn't updated after last changed so it's still working... but from the reference theory I learned from uni, just like he said, it shouldn't work.. Anyone can tell me why it's not updated automatically?(my java version 1.8)
package tst;
public class linkedlsqueue {
private class Node {
String item;
Node next;
}
Node first, last;
public boolean isEmpty() {
return first == null;
}
public void enqueue(String item) {
Node oldlast = last;
last = new Node();
last.item = item;
if (isEmpty()) {
first = last;
}
else {
oldlast.next = last;
}
}
public String dequeue() {
String item = first.item;
first = first.next;
if (isEmpty()) {
last = null;
}
return item;
}
}
Yes, you are correct. It is constant for both cases.
It is a good idea to keep record of both first
and last
for linked list.
Someone call it head
and tail
.
If you maintain only one of last
or first
, you have to search another one by iterating first
to last
to find another one or vice versa - one by one element, which is O(n).
It is like you are in darkness.
You hand holds an end of a rope and you want to know where it will lead to.
I can't think other ways beside tracing that rope. It takes O(n) to trace.
I prefer to use array[] though.
With array, it is like you have a map, a sun, and a super portal (random access).
However, it is not in the scope of the question.
The idea is correct, but the implementation is wrong .
Look at this:
public void enqueue(String item) {
Node oldlast = last;
last = new Node();
last.item = item;
if (isEmpty()) {
first = last;
}
else {
oldlast.next = last;
}
}
when you do oldlast = last
, you DON'T COPY the last
, you just pass last
reference to oldlast
.
During the whole process, oldlast
will be whatever last
is. And in the meanwhile, you RESET the values of last
when you do last = new Node()
.
if you just want to enqueue, the correct method could work like this:
public void enqueue(String item) {
Node newNode = new Node();
newNode.item = item;
if(isEmpty()){
first = newNode; last = newNode;
return;
}
this.last.next = newNode;
this.last = newNode;
}
to copy the element correctly, you should do:
Node oldlast = new Node();
oldlast.item = String(last.item);
hope that helps.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.