trouble implementing a linked list
I'm trying to implement a simple link list. The initial value is inserted successfully, but the next elements are not entered properly. Please help me resolve what the error is. Thanks in appreciation.
#include<iostream>
using std::cout;
class node
{
public:
node():next(0){}
void setNext(node *next){ next = next; }
node* getNext(){ return next; }
void setValue(int val){ value = val; }
int getValue(){ return value; }
private:
int value;
node *next;
};
class list
{
public:
list():head(new node()),len(0){}
bool insert(int value);
//bool remove(int value);
int valueAt(int index);
int length();
private:
node *head;
int len;
};
bool list::insert(int value)
{
node *current = 0;
node *previous = 0;
node *temp = 0;
temp = new node();
temp->setValue(value);
current = head;
previous = head;
while((temp->getValue())>(current->getValue()))
{
previous = current;
current = current-&开发者_开发百科gt;getNext();
if(!current)
{
break;
}
}
if(current == head)
{
temp->setNext(current);
head = temp;
len++;
}
else
{
temp->setNext(current);
previous->setNext(temp);
len++;
}
}
int list::valueAt(int index)
{
if((index < len) && (index >= 0))
{
node *current = 0;
current = head;
int count = 0;
while(count < index)
{
current = current->getNext();
count++;
}
return (current->getValue());
}
else
{
return -1;
}
}
int main()
{
list myList;
myList.insert(5);
myList.insert(20);
myList.insert(10);
cout<<"Value at index 1 : "<<myList.valueAt(1);
return 0;
}
After a cursory glance, perhaps the problem is
void setNext(node *next){ next = next; }
You are assigning a variable to itself, because local variables overshadow instance variables. Try changing that to
void setNext(node *next){ this->next = next; }
In other notes:
In
list::list
, you probably shouldn't initializehead
to anew node
. This will mean your linked list will have one arbitrary node on creation but have a length of 0. You should think about settinghead
toNULL
instead.On creation,
node
s have a randomvalue
. Consider requiring a parameter for that in the constructor, or an appropriate default value.-1
is a bad "invalid value" forlist::valueAt
because it's also a valid value for a node to store.You should probably rename the
list
class toslist
to indicate it stores values in sorted order.
精彩评论