Skip to content

Instantly share code, notes, and snippets.

@pbesra
Created January 12, 2020 19:02
Show Gist options
  • Save pbesra/c13e9bcb5f41af0449f39ab11630dec9 to your computer and use it in GitHub Desktop.
Save pbesra/c13e9bcb5f41af0449f39ab11630dec9 to your computer and use it in GitHub Desktop.
Linked list in C++
#include <iostream>
using namespace std;
class node{
public:
int data;
node* next;
node(int d){
this->data=d;
this->next=NULL;
}
};
class linkedList{
public:
// keeps counts of total number of nodes;
static int nodeCount;
node* add(int d, node* head){
node* nd=new node(d);
nd->next=head;
head=nd;
nodeCount++;
return head;
}
// remove node at a position.
node* removeNode(int position, node* h){
int c=0;
node* current=h;
node* past=h;
if(position<nodeCount){
return h;
}
while(c<position && h!=NULL){
past=h;
h=h->next;
c++;
}
if(position>0 && h!=NULL){
past->next=h->next;
nodeCount--;
}else{
// head is to updated.
nodeCount--;
current=current->next;
}
return current;
}
// inserts node at a position.
node* insertNode(int position, int d, node* h){
node* current=h;
if(position==0){
current=add(d, h);
}else{
int c=0;
node* past=h;
while(c<position && h!=NULL){
past=h;
h=h->next;
c++;
}
if(position<=nodeCount){
node* nd=new node(d);
node* temp=past->next;
past->next=nd;
nd->next=temp;
}
}
return current;
}
//prints node data.
void print(node* h){
if(h==NULL){
return;
}
print(h->next);
cout << h->data << endl;
}
};
// static variable initialization
int linkedList::nodeCount=0;
int main(){
linkedList* ll;
node* h=NULL;
h=ll->add(2, h);
h=ll->add(1, h);
h=ll->add(6, h);
h=ll->add(7, h);
h=ll->add(9, h);
//insertNode index starts at 0.
h=ll->insertNode(9, 10, h);
//remove index starts at 0.
h=ll->removeNode(7, h);
ll->print(h);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment