I am writing a basic Linked List class for a project for my Comp. Sci. class.
How should I go about overloading the [n] operator (n being an integer representing position) so that I can access the nth item in my list? I'm basically trying to emulate how vectors allow coders to access items in the list.
Here's the code from my linked list header:
I started trying it by myself without any help, but I don't know how to write the definition or implementation:
How should I go about overloading the [n] operator (n being an integer representing position) so that I can access the nth item in my list? I'm basically trying to emulate how vectors allow coders to access items in the list.
Here's the code from my linked list header:
Code:
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
const int MAX_VALUE=100; //used to define the maximum length of the linked list
using namespace std;
template <class ItemType> class LinkedList{
private:
struct node{
ItemType item;
node* next;
};
node* start;
int length;
ItemType items[MAX_VALUE];
public:
LinkedList();
void printList();
void insert(ItemType i);
void remove(ItemType i);
int getListLength();
};
template <class ItemType> LinkedList<ItemType>::LinkedList()
{
start=NULL;
//next=NULL;
length=0;
}
template <class ItemType> int LinkedList<ItemType>::getListLength()
{
return length;
}
template <class ItemType> void LinkedList<ItemType>::insert(ItemType i)
{
node* newone=new node;
newone->item=i;
newone->next=start;
start=newone;
length++;
}
template <class ItemType> void LinkedList<ItemType>::remove(ItemType i)
{
node* current=start;
node* trailer=NULL;
if(start==NULL)
{
return;
}
while(current!=NULL && current->item!=i)
{
trailer=current;
current=current->next;
}
if(current==NULL)
{
return;
}
if(current==start)
{
start=start->next;
}
else
{
trailer->next=current->next;
}
delete current;
length--;
}
template <class ItemType> void LinkedList<ItemType>::printList()
{
node* current=start;
if(current==NULL)
{
cout << "List is empty." << endl;
return;
}
while(current!=NULL)
{
cout << current->item << endl;
current = current->next;
}
}
#endif
I started trying it by myself without any help, but I don't know how to write the definition or implementation:
Code:
template <class ItemType> friend ItemType LinkedList<ItemType>::operator[](int posn, ItemType i)
{
node* current=start;
if(posn==0)
return current->item;
while(current!= NULL)
{
//process current node
current = current->next;
}
}