Operator Overloading ‘<<‘ and ‘>>’ operator in a linked list class
Last Updated :
22 Mar, 2023
Prerequisite: Operator Overloading in C++, Linked List in C++
C++ comes with libraries that provide ways for performing Input and Output. In C++, Input and Output are performed as a sequence of bytes, also known as streams. Input and Output stream are managed by the iostream library. cin and cout are the standard objects for the input stream and output stream.
We can overload the ‘>>’ and ‘<<‘ operators to take input in a linked list and print the element in the linked list in C++. It has the ability to provide the operators with a special meaning for a data type, this ability is known as Operator Overloading.
The syntax for overloading an operator are:
returnType operator symbol (arguments)
{
Operations...
}
Overloading the istream operator ‘>>’:
C++
istream& operator>>(istream& is, node*& head)
{
takeInput(head);
}
|
Explanation:
The return type for the above function is a reference to the istream object. In the statement “ cin >> head; “, cin is the first parameter and a reference to the head is the second parameter for the function. The above function is called when any such statement is executed.
Overloading the ostream operator ‘<<‘:
C++
ostream& operator<<(ostream& os, node* head)
{
print(head);
}
|
Explanation:
The return type for the above function is a reference to the ostream object. In the statement “ cout << head;“, cout is the first parameter, and a reference to the head is the second parameter for the function. The above function is called when any such statement is executed.
Code for Overloading of ‘<>’ operator:
Below is the code for overloading of ‘>>’ and ‘<<‘ operators, which takes a number N as an input continuously and insert the number N in the linked list until N = -1.
C++
#include <iostream>
using namespace std;
class node {
public :
int data;
node* next;
node( int d)
{
data = d;
next = NULL;
}
};
void insertAtHead(node*& head, int d)
{
node* n = new node(d);
n->next = head;
head = n;
}
void insertAtTail(node* head, int data)
{
node* n = new node(data);
node* temp = head;
while (temp->next != NULL)
temp = temp->next;
temp->next = n;
}
void print(node* head)
{
if (head != NULL) {
cout << head->data;
head = head->next;
}
while (head != NULL) {
cout << "->" << head->data;
head = head->next;
}
}
void takeInput(node*& head)
{
int n;
cin >> n;
while (n != -1) {
if (head == NULL)
insertAtHead(head, n);
else
insertAtTail(head, n);
cin >> n;
}
}
ostream& operator<<(ostream& os, node* head)
{
print(head);
}
istream& operator>>(istream& is, node*& head)
{
takeInput(head);
}
int main()
{
node* head = NULL;
cin >> head;
cout << head;
return 0;
}
|
Input and Output:
Input: 5 4 3 2 -1
Output: 5->4->3->2
Time Complexity: O(n)
Space Complexity: O(n)
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...