So I made a template...I tried declaring a string linkedlist like so...
LinkedList<string> str;
Then i called the function insertLast to insert a string called hello..like so...
str.insertLast("hello")
Then it gives me null pointer error...I cannot see how there can be a null pointer...help would be appreciated..Here is the insertLast function. The trouble comes on the newNode=new ListNode<T> line...apparently it doesn't like that...and i have no idea why..yes i did use using namespace std;
Here is the function insertLast
void LinkedList<T>::insertLast(T newobj)//O(n)
{
ListNode<T> *newNode;
newNode=new ListNode<T>;
cout<<newobj;
newNode->obj=newobj;
newNode->next=NULL;
ListNode<T> *current;
if(head==NULL){
head=newNode;
tail=newNode;
}
else{
current=head;
while(current->next)
current=current->next;
current->next=newNode;
tail=newNode;
}
}
Here is entire template code
//LinkedList.h
#ifndef LINKEDLIST_H
#define LINKEDLIST_H
#include "RuntimeException.h"
using namespace std;
class LinkedList;
class ListNode {
private:
char obj;
ListNode *next;
friend class LinkedList;
public:
ListNode(char e = 0, ListNode *n = NULL) : obj(e), next(n) { }
char getElem() const { return obj; }
ListNode * getNext() const { return next; }
};
class LinkedList {
private:
ListNode *head, *tail;
public:
// user-defined exceptions
class EmptyLinkedListException : public RuntimeException {
public:
EmptyLinkedListException() : RuntimeException("Empty linked list") {}
};
class InvalidPointerException : public RuntimeException {
public:
InvalidPointerException() : RuntimeException("Attempt to use null pointer") {}
};
LinkedList() {head=NULL; tail=NULL; } // default constructor
~LinkedList() { //O(n)
ListNode *current = head;
ListNode *nextnode;
while(current!=NULL){
nextnode=current->next;
delete current;
current=nextnode;
}
head=NULL;
} // destructor
LinkedList(const LinkedList& ll) {//O(n)
head=NULL;
tail=NULL;
ListNode *current =ll.getHead();
this->insertLast(current->getElem());
while(current->next!=NULL){
current=current->next;
insertLast(current->getElem());
}
} // copy constructor
LinkedList & operator=(const LinkedList & ll); // assignment operator
// query function
int size() const;
bool isEmpty() const {
if (head==NULL) return true;
else return false;
}
// accessor functions
char first() const throw(EmptyLinkedListException);
ListNode *getHead() const { return head; }
ListNode *getTail() const { return tail; }
// update functions
void insertFirst(char newobj);
char removeFirst() throw(EmptyLinkedListException);
void insertLast(char newobj);
void insertAfter(char newobj, ListNode *node) throw(InvalidPointerException);
char remove(ListNode *node) throw(InvalidPointerException);
void removeAll();
friend ostream & operator<<(ostream& out, const LinkedList &ll); //overload <<
};
#endif