I have been working on a linked list for some while now and started out with this.
Is my code clean? Or is there some way to make it better and more readable?
The reason for this question is for me to be a better programmer. I would love to get one step further for making more clean code.
my class:
using namespace std;
class Node
{
public:
int nX;
Node *next;
//constructor
Node(){ head = NULL; } //Initialising head to NULL
void addValueLeft(int nVal);
void addValueRight(int nVal);
void deleteValueLeft();
void deleteValueRight();
void printList();
private:
Node *head; //a pointer to the first Node
};
my main:
int _tmain(int argc, _TCHAR* argv[])
{
using namespace std;
//creating a new object
Node list;
list.addValueLeft(5);
list.addValueLeft(6);
list.addVaueRight(8);
list.deleteValueRight();
list.printList();
return 0;
}
my functions:
void Node::addValueLeft(int nVal)
{
Node *newNode = new Node;
if(!head)
{
newNode->nX = nVal;
newNode->next = NULL;
head = newNode;
}
else
{
newNode->nX = nVal;
newNode->next = head;
head = newNode;
}
}
void Node::printList()
{
if(!head) //list is empty - nothing to print
{
//cout << "nothing to print - list empty " << endl;
}
else
{
Node *tempNode = new Node;
tempNode = head;
while(tempNode)
{
cout << tempNode-> nX << endl;
tempNode = tempNode->next;
}
}
}
void Node::addValueRight(int nVal)
{
Node *tempNode1 = new Node;
if(!head) //List is empty
{
tempNode1 -> nX = nVal;
tempNode1 -> next = head;
head = tempNode1;
}
else
{
tempNode1 = head;
while(tempNode1 -> next != NULL) //Go to last Node
{
tempNode1 = tempNode1->next;
}
Node *tempNode2 = new Node; //create temp node
tempNode2 -> nX = nVal;
tempNode2 -> next = NULL;
tempNode1 -> next = tempNode2; //tempNode1 will be last Node
}
}
void Node::deleteValueLeft()
{
if(!head) //list is empty - Nothing to Delete
{
//cout << " deleteValueLeft: Nothing to delete" << endl;
}
else
{
head = head->next;
}
}
void Node::deleteValueRight()
{
if(head == NULL) //Nothing to delete
{
//cout << "Nothing to delete " << endl;
}
else
{
Node *tempNode1 = new Node;
Node *oldNode = new Node;
tempNode1 = head;
if(tempNode1->next == NULL) //only one element
{
head = NULL;
}
else
{
while(tempNode1->next!=NULL) //Go to last Node
{
oldNode = tempNode1;
tempNode1 = tempNode1->next;
}
oldNode->next = NULL;
}
}
}
Sentinal
it makes the creation of a linked list a lot easier to write and the code a lot cleaner. codereview.stackexchange.com/a/9399/507 \$\endgroup\$ – Martin York Mar 6 '14 at 16:57