c++链表实现2

template 
class Link{
public:
Elem element;//数据域
Link *next;
Link(const Elem& elemval, Link* nextval = NULL){
element = elemval;
next = nextval;
}
Link(Link* nextval = NULL){
next = nextval;
}

};

template
class LList :public list{
private:
Link* head;//头结点
Link* tail;//尾节点
Link* fence;//栅栏结点
int leftcnt; //栅栏结点左边结点的数目
int rightcnt; //栅栏结点右边结点的数目

void init(){
fence = tail = head = new Link;
leftcnt = rightcnt = 0;
}
void removeall(){
while (head != NULL){
fence = head;
head = head->next;
delete fence;
}
}

public:
LList(int size = 0){ init(); }
~LList(){ removeall(); }
void clear(){ removeall(); init(); }

bool insert(const Elem&);
bool append(const Elem&);
bool remove(Elem&);
void setStart(){
fence = head;
rightcnt += leftcnt;
leftcnt = 0;
}
void setEnd(){
fence = tail;
leftcnt += rightcnt;
rightcnt = 0;
}
void prev();
void next(){
if (fence!=tail){
fence = fence->next;
rightcnt--;
leftcnt++;
}
}
int leftLength()const{return leftcnt;}
int rightLength()const{return rightcnt;}
bool setPos(int pos);
bool getValue(Elem& it)const{
if(rightLength()==0)return false;
it = fence->next->element;
return true;
}
void print()const;

bool turn(); //单链表逆序,反转

Link quickloc();//快速定位到中间位置

void getBackN(int N){//寻找单链表倒数第N个数
this->setStart();
while(rightcnt!=N-1){
fence=fence->next;
rightcnt--;
leftcnt++;
}
cout<element;
}

};
template
bool LList::insert(const Elem& item){//在栅栏结点后插入结点
fence->next = new Link(item, fence->next);
if(tail == fence) tail = fence->next;
rightcnt++;
return true;
}


template
bool LList::turn(){//链表就地逆转

Link *current=head->next,*p;
if (head == NULL) {
return false;
}

while (current->next != NULL){
p = current->next;
current->next = p->next;
p->next = head->next;
head->next = p;
}

return true;

}
template
bool LList::append(const Elem& item){//在尾节点后增加结点
tail = tail->next = new Link(item,NULL);
rightcnt++;
return true;
}
template
bool LList::remove(Elem& it){
if(fence->next == NULL)return false;
it = fence->next->element;
Link* ltemp = fence->next;
fence->next = ltemp->next;
if(tail == ltemp) tail =fence;
delete ltemp;
rightcnt--;
return true;
}
template
void LList::prev(){//访问前结点
Link* temp= head;
if(fence == head)return ;
while(temp->next!=fence)temp=temp->next;
fence=temp;
leftcnt--;
rightcnt++;
}
template
bool LList::setPos(int pos){//把栅栏设在pos处
if((pos>0)||(pos>rightcnt+leftcnt))return false;
fence = head;
for(int i=0;inext;
return true;
}
template
void LList::print()const{//打印链表内所有数据及栅栏的当前位置
Link* temp= head;
cout<<"<";
while(temp!=fence){
cout<next->element<<" ";
temp= temp->next;
}
cout<<"|";
while(temp->next !=NULL){
cout<next->element<<" ";
temp=temp->next;
}
cout<<">\n";
}


template
Link LList::quickloc(){//快速定位
Link *search=head,*mid=head;
while(true){
if(search==tail){
cout<element;
return mid;
}
search=search->next;
mid=mid->next;
if(search==tail){
cout<element;
return mid;
}
search=search->next;
}

}

你可能感兴趣的:(技术博客,c++,数据结构)