Você está na página 1de 4

/* Linked List for Integer implementation

*/
#include <iostream>
class list{
private:
struct node{
int data;
node* next;
};
node* head; node* current; node* tmp;
public:
//constructor
list(){
// initializing
head=NULL; current=NULL; tmp=NULL;
}
//add at last
void push(int value){
// create a node and
node* newNode = new node;
newNode->data = value;
newNode->next = NULL;
if(head==NULL){
head = newNode;
return;
}else{
current = head;
while(current->next != NULL){
current = current->next;
}
}
current->next = newNode;
}
// insert value @ location
void insert(int value,int index){
// create a node and
node* newNode = new node;
newNode->data = value;
// newNode->next = NULL; //-> after
register int count = 0;
if(head==NULL){
if(index==0){
newNode->next = NULL;
head=newNode;
}
else{return;}
}
else{
//tmp for saving previous node =>
current = head; tmp=head;
while(current->next != NULL){

if(count==index){
// for head node head=>new node & new no
de =>next = head
if(index==0){
newNode->next = head;
head = newNode;
}
// for other tmp =><= newnode =><= curre
nt
else{
newNode->next = current;
tmp->next = newNode;
}
return;
}
else{
tmp=current;
current = current->next;
count++;
}
// for tail which wasn't captured by while
if(count==index){
newNode->next = current;
tmp->next = newNode;
}
}
}
}
// remove from index
void remove(int index){
int count = 0;
current = head; tmp=head;
if(head==NULL){return;}
else{
while(current->next!=NULL){
if(count == index){
if(index==0){
head=current->next;
delete current;
}
else{
tmp->next=current->next->next;
delete current;
}
}
tmp = current;
current = current->next;
count++;
}
if (count==index)
{
tmp->next=NULL;
delete current;
}

}
}
//easy access
int operator[](int index){
int count = 0;
current = head;
while(current->next!=NULL){
if(count==index){
return current->data;
}
else{
current=current->next;
count++;
}
}
if(count==index){
return current->data;
}
else{
return -1;
}
}
void printAll(){
if(head==NULL){
return;
}
else{
current = head;
// breaks here null dont have ->next
while(current->next != NULL){
std::cout << current->data << "\n";
current = current->next;
}
if(current != NULL){
std::cout << current->data << "\n";
}
}
}
//destructor
~list(){}
};
int main(){
list myll;
myll.push(5);
myll.push(7);
myll.push(45);
myll.insert(3,1);
myll.insert(44,0);
myll.insert(89,4);

myll.insert(66,5);
myll.remove(6);
myll.printAll();
std::cout << myll[10] << " <- \n";
// list mylls[10];
//ending
std::cout<< "\npress any key to continue...";
std::cin.get();
return 0;
}

Você também pode gostar