Linked list insertion Head Linked list insertion Head Node n new Node n Linked list insertion Head t mp Assume tmp points to the node before the place that we want to enter our new node n Linked list insertion ID: 768354
Download Presentation The PPT/PDF document "Linked list insertion" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Linked list insertion Head
Linked list insertion Head Node n = new Node(); n
Linked list insertion Head t mp Assume tmp points to the node before the place that we want to enter our new node. n
Linked list insertion Head Tmp n.setNext ( tmp.getNext ()); n
Linked list insertion Head Tmp tmp.setNext (n); n
Inserting at the head node 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.setNext (head); n
Inserting at the head node Head We don't need a tmp pointer here. head = n; n
Inserting at the tail node Head Inserting at the end is not a special case! We still need a tmp pointer pointing to the node before ( ie the last node). n Tmp
Inserting at the tail node Head And then, as before… n Tmp n.setNext ( tmp.getNext ()); Note this just sets n's pointer to null.
Inserting at the tail node Head And then, as before… n Tmp tmp.setNext (n);
What happens to tmp and n? Head They are local variables, so they will disappear as soon as the insert method returns.
Recap Head 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
Linked Lists over Arrays Head No size limit Can expand as you need Easy to add nodes anywhere Sequential access only, no direct access