Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A modular object oriented class based implementation of Linked List
#include<bits/stdc++.h>
using namespace std;
class Node {
int key;
Node* next;
public:
int getKey() {
return key;
}
void setKey(int val) {
key = val;
}
Node* getNext() {
return next;
}
void setNext(Node* node) {
next = node;
}
};
class LinkedList {
Node *head;
public :
// constructor
LinkedList() {
head = NULL;
}
void insertAtBeginning(int value) {
Node* toBeInserted = new Node(); // instantiating a new object of Node class
toBeInserted->setKey(value); // setting key
toBeInserted->setNext(NULL); //setting next
// condition to check for empty list
if (!head)
head = toBeInserted;
else {
toBeInserted->setNext(head);
head = toBeInserted;
}
}
vector<int> printLL()
{
vector<int> ll;
Node* temp = head;
while(temp) {
ll.push_back(temp->getKey());
temp = temp->getNext();
}
return ll;
}
};
int main() {
LinkedList newLL;
newLL.insertAtBeginning(3);
newLL.insertAtBeginning(4);
newLL.insertAtBeginning(5);
newLL.insertAtBeginning(6);
newLL.insertAtBeginning(7);
newLL.insertAtBeginning(8);
vector<int> ll = newLL.printLL();
for(auto i: ll) {
cout << i << " ";//auto creates a class so * won't come.
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment