Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Note: See "linktester.cpp" for more information.
- */
- #ifndef LINKEDLIST_CPP
- #define LINKEDLIST_CPP
- #include <iostream>
- #include <new>
- using namespace std;
- #include "LinkedList.h"
- LinkedList::LinkedList()
- {
- first = 0;
- mySize = 0;
- }
- LinkedList::LinkedList(const LinkedList & origList)
- {
- mySize = origList.mySize;
- if(origList.mySize == 0)
- {
- first = NULL;
- }
- else
- {
- Node * origPtr = origList.first;
- LinkedList::NodePointer lastPtr = new(nothrow) Node(origPtr->data);
- first = lastPtr;
- origPtr = origPtr->next;
- for(int i = 0; i < size()-1; i++)
- {
- lastPtr->next = new Node(origPtr->data);
- lastPtr = lastPtr->next;
- origPtr = origPtr->next;
- }
- }
- }
- LinkedList::~LinkedList()
- {
- Node * ptr = first;
- for(int i = 0; i < size(); i++)
- {
- first = ptr -> next;
- delete ptr;
- ptr = first;
- }
- if(first == 0) cout << "List destroyed\n";
- else cout << "List not destroyed\n";
- }
- int LinkedList::size()
- {
- return mySize;
- }
- void LinkedList::display(ostream & out) const
- {
- LinkedList::NodePointer ptr = first;
- while(ptr != NULL)
- {
- out << ptr->data << " ";
- ptr = ptr->next;
- }
- }
- void LinkedList::insert(int index, int dataValue)
- {
- LinkedList::NodePointer nPtr = new(nothrow) Node(dataValue);
- if(index > size()|| index < 0)
- {
- cout << "Index out of range. " << endl;
- return;
- }
- mySize = mySize+1;
- if(index == 0) // insert at the beginning of the list
- {
- nPtr->next = first;
- first = nPtr;
- }
- else
- {
- LinkedList::NodePointer predPtr = first;
- for(int i = 0; i < (index-1); i++)
- {
- predPtr = predPtr->next;
- }
- nPtr->next = (predPtr->next);
- predPtr->next = (nPtr);
- }
- }
- void LinkedList::erase(int index)
- {
- LinkedList::NodePointer prevPtr = first;
- LinkedList::NodePointer ptr = first;
- if(index > (LinkedList::size()-1) || index < 0) //out of range
- {
- cout << "The requested index to erase is out of range. " << endl;
- return;
- }
- if(index == 0) // erase first item
- {
- first = prevPtr->next;
- }
- else
- {
- Node * predPtr = first;
- for(int i = 0; i < index-1; i++)
- {
- predPtr= predPtr->next; //get to the proper index in the list
- }
- ptr = predPtr->next; // ptr points to the node to be deleted.
- if(ptr->next != NULL)
- {
- predPtr->next = ptr->next;
- delete ptr;
- }
- else
- {
- delete ptr;
- predPtr->next = NULL;
- }
- }
- mySize = mySize-1;
- return;
- }
- ostream & operator<< (ostream & out, const LinkedList &list)
- {
- list.display(out);
- return out;
- }
- LinkedList& LinkedList::operator=(const LinkedList& list)
- {
- if(this == &list)
- return *this;
- else
- {
- this->~LinkedList();
- LinkedList l(list);
- return *this;
- }
- }
- LinkedList::Node::Node(int dataVal)
- {
- data = dataVal;
- next = NULL;
- }
- #endif
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement