Skip to content

Instantly share code, notes, and snippets.

@dkp1903
Created May 22, 2021 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dkp1903/bb7fd2a40d97f81ef59576f333c669d0 to your computer and use it in GitHub Desktop.
Save dkp1903/bb7fd2a40d97f81ef59576f333c669d0 to your computer and use it in GitHub Desktop.
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