Download presentation
Presentation is loading. Please wait.
Published byGlenna Sucianty Gunawan Modified over 6 years ago
2
Linked list insertion Head
3
Linked list insertion Node n = new Node(); Head n
4
Linked list insertion tmp
Assume tmp points to the node before the place that we want to enter our new node. tmp Head n
5
Linked list insertion n.setNext(tmp.getNext()); Tmp Head n
6
Linked list insertion tmp.setNext(n); Tmp Head n
7
Inserting at the head node
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. Head n n.setNext(head);
8
Inserting at the head node
We don't need a tmp pointer here. Head n head = n;
9
Inserting at the tail node
Inserting at the end is not a special case! We still need a tmp pointer pointing to the node before (ie the last node). Tmp Head n
10
Inserting at the tail node
And then, as before… Tmp Head n n.setNext(tmp.getNext()); Note this just sets n's pointer to null.
11
Inserting at the tail node
And then, as before… Tmp Head n tmp.setNext(n);
12
What happens to tmp and n?
They are local variables, so they will disappear as soon as the insert method returns. Head
13
Recap Create the new node Should it go at the head?
If yes insert it using the method above If not find the node before the place it should go and insert using the method shown Head
14
Linked Lists over Arrays
No size limit Can expand as you need Easy to add nodes anywhere Sequential access only, no direct access Head
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.