STL is one of the pillars of C++. It makes life lot easier, especially when your focus is on problem solving and you don’t want to spend time in implementing something that is already available which guarantees a robust solution. One of the key aspects of Software Engineering is to avoid reinventing the wheel. Reusability is always preferred.
While relying on library functions directly impacts our efficiency, without having a proper understanding of how it works sometimes loses meaning of the engineering efficiency we keep on talking. A wrongly chosen data structure may come back sometime in future to haunt us. The solution is simple. Use library methods, but know how does it handles operations under the hood.
Enough said! Today we will look on how we can implement our own Iterator pattern of a single Linked List. So, here is how an STL implementation of Linked List looks like:
1 2 3
One of the beauty of cin and cout is that they don’t demand format specifiers to work with the type of data. This combined with templates make the code much cleaner and readable. Although I prefer naming method in C++ start with caps, this implementation follows STL rules to mimic exact set of method calls, viz push_back, begin, end.
Here is our own implementation of LinkedList and its Iterator pattern:
Traversing LinkedList through method 1 2 3 Traversing LinkedList through Iterator 1 2 3
The above implementation works well when we have one data. Extend this code to work for set of data wrapped in a class.
This article is contributed by Aashish Barnwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Facade Design Pattern | Introduction
- Remove all occurrences of duplicates from a sorted Linked List
- Descending order in Map and Multimap of C++ STL
- Binary Search functions in C++ STL (binary_search, lower_bound and upper_bound)
- Move all occurrences of an element to end in a linked list
- Array Type Manipulation in C++
- Circular Singly Linked List | Insertion
- Adding two polynomials using Linked List
- Length of longest palindrome list in a linked list using O(1) extra space
- Clone a linked list with next and random pointer in O(1) space
- Check linked list with a loop is palindrome or not
- Flyweight Design Pattern
- Curiously recurring template pattern (CRTP)
- Iterator Pattern
- Linked List | Set 1 (Introduction)