#ifndef LINKEDLIST_H #define LINKEDLIST_H #include "stdafx.h" #include <iostream> using namespace std; /* ---data definition---*/ template <typename T> struct Node /* a node in a list*/ { T data; struct Node *next; }; /*---functions declarations for linked list---*/ template <typename T> class LinkedList { Node<T> * head; Node<T> *prev; Node<T> *end; Node<T> *curr; int length; public: LinkedList() /*initial the head node*/ { head=new Node<T>; head->data=0; head->next=NULL; prev=head; end=head; curr=head; length=0; } Node<T> * CreateList(T elem); /*create a new list*/ void DisplayList(); /*Display the list*/ bool IsFull(); /*judge the enough space*/ bool IsEmpty(); /*judge a empty list*/ int getLength()const; /*get the length*/ Node<T> *InsertElem(int num,T elem); /*insert a node to the list*/ Node<T> *DeleteElem(int num); /*delete a node*/ Node<T> *EmptyList(); /*empty a list*/ ~LinkedList() /*destroy the list*/ { delete head; delete prev; delete curr; length=0; } }; /*---function of linked list*/ template<typename T> bool LinkedList<T>::IsFull() { try { Node<T> *tmp=new Node<T>; delete tmp; return false; } catch(std::bad_alloc exception) { return true; } } template<typename T> bool LinkedList<T>::IsEmpty() { if(length==0&&head->next==NULL)return true; else return false; } template<typename T> Node<T>* LinkedList<T>::CreateList(T elem) { if(!IsFull()) { Node<T> *tmp=new Node<T>; tmp->data=elem; tmp->next=NULL; if(IsEmpty()) { end=head; end->next=tmp; end=end->next; ++length; } else { end->next=tmp; end=end->next; ++length; } } return head; } template<typename T> void LinkedList<T>::DisplayList() { curr=head; if(length==0&&head->next==NULL)cout<<"Please create a new list"<<"/n"; else { while(curr->next!=NULL) { cout<<curr->data<<" "; curr=curr->next; } cout<<curr->data; } } template<typename T> int LinkedList<T>::getLength()const { return length; } template<typename T> Node<T> *LinkedList<T>::InsertElem(int num,T elem) { if(!IsFull()) { int n=num-1; Node<T> *tmp=new Node<T>; tmp->data=elem; tmp->next=NULL; prev=head; curr=head; while(n!=0) { prev=prev->next; --n; } curr=prev->next; prev->next=tmp; tmp->next=curr; ++length; } return head; } template<typename T> Node<T> *LinkedList<T>::DeleteElem(int num) { if(!IsEmpty()) { curr=head; prev=head; int n=num-1; while(n!=0) { prev=prev->next; --n; } Node<T> *tmp=new Node<T>; tmp=prev->next; curr=tmp->next; prev->next=curr; --length; delete tmp; } return head; } template<typename T> Node<T> *LinkedList<T>::EmptyList() { curr=head->next; while(curr->next!=NULL)curr->data=0; curr->data=0; return head; } #endif // Linked List.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "linkedlist.h" using namespace std; int _tmain(int argc, _TCHAR* argv[]) { LinkedList<int> A; int i=5; while(i!=0) { A.CreateList(i); --i; } A.InsertElem(3,9); A.DeleteElem(2); A.DisplayList(); cout<<"/n"; cout<<A.getLength()<<"/n"; A.EmptyList(); A.DisplayList(); system("pause"); return 0; }