/*
* LinkedList.h
*
* Created on: Mar 9, 2014
* Author: steven
*/
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include <iostream>
using std::cout;
using std::endl;
template<class T>
class LinkedList {
template<class E>
struct Node {
Node<E> *rightNode;
E data;
Node() {
rightNode = NULL;
}
};
private:
Node<T> *startNode;
int size;
public:
LinkedList() {
startNode = NULL;
size = 0;
}
void pushFront(T data) {
if (size > 0) {
Node<T> *temp = new Node<T>();
temp->data = data;
temp->rightNode = startNode;
startNode = temp;
size++;
return;
}
pushBack(data);
}
void pushBack(T data) {
if (size > 0) {
Node<T> *temp = startNode;
for (int i = 0; i < size - 1; i++) {
temp = temp->rightNode;
}
temp->rightNode = new Node<T>();
temp->rightNode->data = data;
size++;
return;
}
startNode = new Node<T>();
startNode->data = data;
size++;
}
T get(int num) {
if (num > 0) {
Node<T> * temp = startNode; //1
for (int i = 0; i < num - 1; i++) {
temp = temp->rightNode;
}
T tempData = temp->rightNode->data;
delete temp;
return tempData;
} else {
return startNode->data;
}
}
void removeBack() {
if (size > 2) {
Node<T> *temp = startNode;
for (int i = 0; i < size - 2; i++) {
temp = temp->rightNode;
}
delete temp->rightNode;
temp->rightNode = NULL;
} else if (size == 2) {
delete startNode->rightNode;
startNode->rightNode = NULL;
} else {
delete startNode;
startNode = NULL;
}
size--;
}
void printLinkedList() {
Node<T> *temp = startNode;
cout << temp->data << endl;
for (int i = 0; i < size - 1; i++) {
temp = temp->rightNode;
cout << temp->data << endl;
}
}
int getSize() {
return size;
}
virtual ~LinkedList() {
if (size > 2) {
Node<T> *temp = startNode;
while (temp->rightNode->rightNode != NULL) {
Node<T> *currentTemp = temp;
temp = temp->rightNode;
delete currentTemp;
}
return;
}
if (size == 1) {
delete startNode;
return;
}
if (size == 2) {
delete startNode->rightNode;
delete startNode;
return;
}
}
};
#endif /* LINKEDLIST_H_ */
Please critique the singly linked list, specifically the working aspect of it (making sure deleting correctly, etc.).
getSize()
should beconst
. I also see that this wasn't corrected from your previous question. You should ideally be showing some improvement with each question asked. – Jamal♦ Mar 9 '14 at 22:30Node
to be templated: you only useNote<T>
everywhere. – Morwenn Mar 9 '14 at 22:49