Todays Agenda q Linked Lists q Double ended
Today’s Agenda q Linked Lists q Double ended Linked Lists q Doubly Linked Lists CS 2336: Computer Science II
Linked List q Made up of Nodes q Each node has q An item q A reference to next node in the list l 1 item next 7 l 2 item 0 next CS 2336: Computer Science II l 3 item next 6
Advantages over array q Inserting item into middle of linked. List takes constant time if you have reference to the node q The list can keep growing until memory runs out CS 2336: Computer Science II
Inserting an item q Insert a new item immediately after “this” node. q insert. After method l 1 item next 7 l 2 item 0 next item l 3 next item next CS 2336: Computer Science II 3 6
Disadvantages over array q Finding the nth item of a linked. List takes O(n) because it is proportional to size of the list. q But in array you can do it in constant time q A lot of data structures that we will see in this course are trying to find a solution that works quickly in all the different cases both finding and inserting new items CS 2336: Computer Science II
Find nth position q First we check , if the position is equal to 1 then we find the solution and return this q Then we check if the position is less than 1 or our list is empty (next is null) , so return null q If none of the above, then we use recursion. q The idea is that if I jump forward one node or I jump to the next reference then I can call nth recursively on that node and the position is one less. 4 th This CS 2336: Computer Science II 3 th
Linklist Contact. Name List Example CS 2336: Computer Science II
Double ended linked list q Think about a neighborhood with neighbors q First we create neighbor object q Double ended has both reference to the first and the last link in the list q Firstlink and lastlink q Add new neighbor to the beginning of the list q Add new neighbor to the end of the list CS 2336: Computer Science II
Doubly linked list q Unlike the other list that they only had value next and they could only go forward, we have value previous so we can go backward too. q Add after a specific key q Add on order CS 2336: Computer Science II
- Slides: 9