數據結構練習--單向鏈表的實現

自己學習數據結構,寫的第一個單向鏈表,水平真是差的要命,查了那麼多相關的構造方法,不斷的改,才實現這麼個一個拙漏的一個方法,看來還得是自己慢慢學習,這個就當作一個成果吧,一點一點努力


#include<iostream>

using namespace std;
template<class T>
class Node
{
public:
T data;
Node<T> *next;
};
template<class T>
class myslist
{
private:
Node<T>*node;
Node<T>*headnode;
Node<T>*lastnode;
unsigned int length;
public:
myslist();
void add(T x);
void add_front(T x);
void Delete(T x);
int find(T x);
bool isEmpty();
void output();
~myslist();

};
template<class T>
myslist<T>::myslist()
{
node=NULL;
headnode=NULL;
lastnode=NULL;
length=0;
};
template<class T>
void myslist<T>::add(T x)
{
node=new Node<T>();
node->data=x;
if(headnode==NULL)
{
headnode=node;
   lastnode=node;
}
else
{
lastnode->next=node;
   lastnode=node;
}
++length;
};


template<class T>
void myslist<T>::add_front(T x)
{
node=new Node<T>();
node->data=x;
if(headnode==NULL)
{
headnode=node;
lastnode=node;
}
else
{
node->next=headnode;
headnode=node;
}
++length;
};
template<class T>
void myslist<T>::Delete(T x)
{
Node<T>*temp=headnode;
if(temp==NULL)
{
cout<<"NO"<<endl;
       return ;
}
else if(temp->data==x)
{
headnode=temp->next;
if(temp->next==NULL)
lastnode=NULL;
delete(temp);
return;
}
while(temp->next!=NULL&&temp->next->data!=x)
{
temp=temp->next;
}
if(temp->next==NULL)
return;
if(temp->next==lastnode)
{
lastnode=temp;
delete(temp->next);
temp->next=NULL;
}
else
{
node=temp->next;
temp->next=node->next;
delete(node);
node=NULL;
}
--length;
};
template<class T>
int myslist<T>::find(T x)
{
node=headnode;
while(node!=NULL&&node->data!=x)
{
node=node->next;
}
if(node==NULL)
return -1;
else
return node->data;
};
template<class T>
bool myslist<T>::isEmpty()
{
if(headnode==NULL)
return true;
else
return false;
};
template<class T>
void myslist<T>::output()
{
node=headnode;
while(node!=NULL)
{
cout<<node->data<<" ";
node=node->next;
}
cout<<endl;
};
template<class T>
myslist<T>::~myslist()
{
delete headnode;
}
int main()
{
myslist<int> ilist;
Node<int> ilist1;


ilist.add(70);


cout<<"please input values: "<<endl;
int x,y;
while(1){
cin>>x;
ilist.add(x);
cout<<"please input values: "<<endl;
if(x==-1)
{
ilist.Delete(-1);
break;
}

cout<<endl;
}
ilist.output();
ilist.add_front(90);
ilist.add_front(80);
ilist.output();
cout<<"請輸入要查找的第幾個數:"<<endl;
cin>>y;
int value=ilist.find(y);
if(value==-1)
cout<<"no"<<endl;
else
cout<<"你要找的是: "<<value<<endl;
    ilist.Delete(80);
ilist.output();
cout<<endl;
cout<<endl;


return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章