Download presentation
Presentation is loading. Please wait.
1
Recursive Linked List Operations
A non-empty linked list consists of a head node followed by the rest of the nodes The rest of the nodes form a linked list that is called the tail of the original list
2
Recursive Linked List Operations
Many linked list operations can be broken down into the smaller problems of processing the head of the list and then recursively operating on the tail of the list
3
Recursive Linked List Operations
To find the length (number of elements) of a list If the list is empty, the length is 0 (base case) If the list is not empty, find the length of the tail and then add 1 to obtain the length of the original list
4
Recursive Linked List Operations
Using recursion to display a list: void displayList(ListNode *myList) { if (myList != NULL) cout << myList->data << " "; displayList(myList->next); } See pr17-07.cpp
5
Other Recursive Linked List Operations
Insert and remove operations can be written to use recursion General design considerations: Base case is often when the list is empty Recursive case often involves the use of the tail of the list (i.e., the list without the head). Since the tail has one fewer entry than the list that was passed in to this call, the recursion eventually stops. See NumberList2.cpp, NumberList2.h, and pr17-08.cpp
6
The STL list Container template version of a doubly linked list
can insert/add elements more quickly than vectors can add efficiently add elements to the end of the list, because of the built-in pointer to the last element See pr17-09.cpp
7
list Member Functions back
returns a reference to the last element in the list erase erases element (or erase elements from first to last) empty returns true if list is empty; false otherwise end returns an iterator to the end of the list front returns a reference to the first element of the list insert inserts an element into the list merge for two sorted lists, insert each element of list 2 into list 1 pop_back removes the last element of the list pop_front removes the first element of the list push_back inserts an element at the end of the list push_front inserts an element at the beginning of the list reverse reverses the order in which the elements appear in the list size returns the number of elements in the list swap swaps the elements stored in two lists unique eliminates duplicate values by eliminating any element that has the same value as the element before it See pr17-09.cpp
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.