Experiment 7
Aim
To develop a template of the Linked List class and its
methods using C++ class templates.
Objectives
- To
understand class templates.
- To
implement a generic linked list.
- To
perform insertion, deletion and display operations.
- To
understand generic data structures.
Theory
Templates allow a class or function to operate on different
data types without rewriting the code.
A linked list consists of nodes where each node contains
data and a pointer to the next node.
Program
#include <iostream>
using namespace std;
template <class T>
class LinkedList {
struct Node {
T data;
Node *next;
Node(T x) {
data = x;
next =
NULL;
}
};
Node *head;
public:
LinkedList() {
head = NULL;
}
void insert(T x) {
Node *n = new
Node(x);
n->next =
head;
head = n;
}
void remove() {
if (head ==
NULL) {
cout
<< "List is empty\n";
return;
}
Node *temp =
head;
head =
head->next;
delete temp;
}
void display() {
Node *p =
head;
while (p !=
NULL) {
cout
<< p->data << " ";
p =
p->next;
}
cout <<
endl;
}
};
int main() {
LinkedList<int> list;
list.insert(10);
list.insert(20);
list.insert(30);
cout <<
"List: ";
list.display();
list.remove();
cout <<
"After deletion: ";
list.display();
return 0;
}
Result
Thus, a generic Linked List class template and its
basic methods were successfully implemented.
No comments:
Post a Comment