Head Linked list insertion Linked list insertion n

  • Slides: 14
Download presentation

Head Linked list insertion

Head Linked list insertion

Linked list insertion n Head Node n = new Node();

Linked list insertion n Head Node n = new Node();

n Head tmp Linked list insertion Assume tmp points to the node before the

n Head tmp Linked list insertion Assume tmp points to the node before the place that we want to enter our new node.

Linked list insertion n Head Tmp n. set. Next(tmp. get. Next());

Linked list insertion n Head Tmp n. set. Next(tmp. get. Next());

Linked list insertion n Head Tmp tmp. set. Next(n);

Linked list insertion n Head Tmp tmp. set. Next(n);

Inserting at the head node n Head This time we cannot get a pointer

Inserting at the head node n Head This time we cannot get a pointer to the node before the place we want to enter our new node! So inserting at the head is a special case. n. set. Next(head);

Inserting at the head node n Head We don't need a tmp pointer here.

Inserting at the head node n Head We don't need a tmp pointer here. head = n;

Inserting at the tail node n Head Tmp Inserting at the end is not

Inserting at the tail node n Head Tmp Inserting at the end is not a special case! We still need a tmp pointer pointing to the node before (ie the last node).

Inserting at the tail node n. set. Next(tmp. get. Next()); Note this just sets

Inserting at the tail node n. set. Next(tmp. get. Next()); Note this just sets n's pointer to null. n Head Tmp And then, as before…

Inserting at the tail node tmp. set. Next(n); n Head Tmp And then, as

Inserting at the tail node tmp. set. Next(n); n Head Tmp And then, as before…

What happens to tmp and n? Head They are local variables, so they will

What happens to tmp and n? Head They are local variables, so they will disappear as soon as the insert method returns.

Recap Head 1. Create the new node 2. Should it go at the head?

Recap Head 1. Create the new node 2. Should it go at the head? 3. If yes insert it using the method above 4. If not find the node before the place it should go and insert using the method shown

Linked Lists over Arrays Head 1. No size limit 2. Can expand as you

Linked Lists over Arrays Head 1. No size limit 2. Can expand as you need 3. Easy to add nodes anywhere 4. Sequential access only, no direct access