rena-c
rena-c

Reputation: 325

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?

Upvotes: 3

Views: 1190

Answers (1)

Bozho
Bozho

Reputation: 597362

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)

Upvotes: 1

Related Questions