您的位置:首页 > 理论基础 > 数据结构算法

数据结构练习--单向链表的实现

2013-03-23 22:12 513 查看
自己学习数据结构,写的第一个单向链表,水平真是差的要命,查了那么多相关的构造方法,不断的改,才实现这么个一个拙漏的一个方法,看来还得是自己慢慢学习,这个就当作一个成果吧,一点一点努力

#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;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: