Download presentation
Presentation is loading. Please wait.
Published byDevi Setiabudi Modified over 6 years ago
1
Linked lists Motivation: we can make arrays, but their functionality is slightly limited and can be difficult to work with Biggest issue: size management We can do dynamic arrays, but can be cumbersome to add more cells if needed Internal re-structuring is difficult To insert or delete elements after array creation and population, we must move potentially many elements around
2
Linked lists Each element (node) of the list will have a pointer to the next one. There will always be a list “head” which is just a pointer to the first element of the list
3
Simple Linked List class
Will be defined in an ad-hoc way, for a list of a specific data type Needs to have certain operations: Insert Delete Append Print
4
Basic Singly Linked list
class NumberList { private: struct ListNode{ double value; struct ListNode *next; }; ListNode *head; public: NumberList(){ head = nullptr; } ~NumberList(); void appendNode(double); void insertNode(double); void deleteNode(double); bool contains(double); void displayList() const; }
5
List Append General algorithm:
Start with the head of the list, if it is null, point it to the new element If the head was not null, check the *next pointer to see if it is null. If it is null, point it at the new element If it is not null, Repeat step 2 on this element Head / 5 myList->append(6) cursor 6
6
List search Given: element value “x” to determine if it is present
Iterate each element of the array, using the “next” pointer If the current node is not “x”, move to the “next” element and repeat If the current node is “x”, return true myList->contains(-2) / 3 -2 10 cursor return true;
7
List (linear) Search bool NumberList::contains(double val){ ListNode *cursor = head; while ( cursor && cursor->value != val ){ cursor = cursor->next; if ( cursor ) // will be null when we’ve run out return true; }
8
List Insert General algorithm:
If the list is empty, point head at the new element Otherwise, find the node “before” the new one (or as specified) Set the *next pointer of the new element to the previous element’s *next Set the *next of the previous element to the new element Head / 5 10 cursor myList->insertAfter(5,6) 6
9
list delete Given: value “x” of element we want to remove Procedure:
Use same search as before, but modify so that when you find the element, cut it out of the list If you find “x” Join the previous node’s “next” pointer to x’s next node Delete the object from memory myList->delete(-2) / 3 -2 10 cursor
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.