Linked List

LinkedList.h

#ifndef LINKEDLIST_H
#define LINKEDLIST_H
struct Link {
	int num;
	Link* next;
};
class LinkedList{
private:
	Link *first,*last;
public:
	LinkedList();	// default constructor
	LinkedList(unsigned size,int uniformValue); // initialize a list with size element of uniformValue
	LinkedList(int *start, int *end); // initialize a list from start to end (not included end)
	void push_front(int value);	// add new item to the front of the list
	void push_back(int value);	// add new item to the end of the list
	int size();					// return the size of the list
	void display();				// display content of the list
	int operator [](unsigned index);	// overloading operator []
	int front();		// return the first element of the list
	int back(); 		// return the last element of the list
};
#endif

LinkedList.cc

#include <iostream>
#include <climits>
#include "LinkedList.h"
using namespace std;
//default constructor
LinkedList::LinkedList():first(NULL),last(NULL){}
// initialize a list with size element of uniformValue
LinkedList::LinkedList(unsigned size,int uniformValue){
	Link* arr=new Link[size];
	for (unsigned ii=0;ii<size;++ii){
		arr[ii].num=uniformValue;
		if (ii<size-1) arr[ii].next=arr+ii+1;
		else arr[ii].next=NULL;
	}
	first=arr;
	last=arr+size-1;
}
// initialize a list from start to end (not included end)
LinkedList::LinkedList(int *start, int *end){
	int size=end-start;
	Link* arr=new Link[size];
	for (unsigned ii=0;ii<size;++ii){
		arr[ii].num=*(start+ii);
		if (ii<size-1) arr[ii].next=arr+ii+1; 		else arr[ii].next=NULL; 	} 	first=arr; 	last=arr+size-1; } // add a new item to the front of the list void LinkedList::push_front(int value){ 	Link* pt=new Link;	//create a new atom  	pt->num=value;
	pt->next=first;
	first=pt;
	if (last==NULL) last=first; // if there is only one entity in the list so first=last
}
// add a new item to the back for the list
void LinkedList::push_back(int value){
	Link* pt =new Link;
	pt->num=value;
	pt->next=NULL;
	if (last==NULL) {
		last=pt;
		first=last;
	}else{
		last->next=pt;
		last=pt;
	}
}
// return the size of the list
int LinkedList::size(){
	Link* pt(first);
	int count(0);
	while(pt!=NULL){
		count++;
		pt=pt->next;
	}
	return count;
}
// display the content of the list
void LinkedList::display(){
	Link* pt(first);
	while(pt!=NULL){
		cout<<"["<<pt->num<<"]"; 		pt=pt->next;
	}
	cout<<endl; } // overloading operator [] int LinkedList::operator [] (unsigned index){ 	Link* pt(first); 	int count(0); 	while(pt!=NULL){ 		if (count==index) { 			return pt->num;
			break;
		}
		count++;
		pt=pt->next;
	}
	if (pt==NULL) return INT_MAX;
}
// return the first element of the list
int LinkedList::front(){
	if (first==NULL) return INT_MAX;
	return first->num;
}
// return the last element of the list
int LinkedList::back(){
	if (last==NULL) return INT_MAX;
	return last->num;
}
Advertisements