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.
- Implementing a Linked List in Java using Class
- Find the second last node of a linked list in single traversal
- Implementing Forward Iterator in BST
- Iterator Pattern
- Create new linked list from two given linked list with greater element at each node
- Merge a linked list into another linked list at alternate positions
- Difference between Singly linked list and Doubly linked list
- Convert singly linked list into circular linked list
- XOR Linked List – A Memory Efficient Doubly Linked List | Set 2
- XOR Linked List - A Memory Efficient Doubly Linked List | Set 1
- How to delete a range of values from the List using Iterator
- Convert Singly Linked List to XOR Linked List
- Check if a linked list is Circular Linked List
- Construct a Maximum Sum Linked List out of two Sorted Linked Lists having some Common nodes
- Create a linked list from two linked lists by choosing max element at each position