Linked List Structure in Java
i have a question about circularly linked lists. My linked list object has two references, first
and last
, and the next node of the last
reference is first
. I want to write a method that inserts a node into the end of the list.
void insertLast(int k) {
Node a = new Node(k);
if (first == null) {
first = last = a;
} else {
last.after = a;
开发者_JAVA技巧 a.after = first;
}
last = a
}
Is something like this possible? Have I made a mistake?
Yes, it is.
- let the current last point to the new one (
last.setNext(newNode)
) - let the new one point to the first (
newNode.setNext(first)
) - set the last to be the new node (
last = newNode
)
精彩评论