Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
        a.after = first;
    }

    last = a
}

Is something like this possible? Have I made a mistake?

like image 824
rena-c Avatar asked Jul 14 '26 13:07

rena-c


1 Answers

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)
like image 173
Bozho Avatar answered Jul 16 '26 01:07

Bozho



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!