c++ 用模板类创建一个单向链表 实现链表节点的增加、删除、输入 怎么写啊

应该是输出 用模板设计一个通用的单向链表类list,实现链表节点的增加、删除、查找、以及链表数据的输出操作

#include <iostream>
using namespace std;
struct node
{
int data;
node *next;
node(){ next=NULL;}
};
class link
{
public:
link();
~link();
void creat(); //调用creat1函数 ,完成链表的建立工作
void creat1(int num); //构建链表的函数
bool search(int i); //查找第i个节点的数据,并输出
bool insert (int i,int number); //在第i个节点插入数据number
bool shanchu(int i,int &x); //删除第i个节点
void output(node *f); //输出链表中所有节点的值

node *first;
node *rear;
int size;
};

link::link()
{
size=0;
first=new node;
rear=first;
first->next=NULL;
}
link::~link()
{
while (first)
{
node *p=first;
delete first;
first=p->next;
}
}

void link::creat()
{
int i,j,m;
cout<<"请输入要输入数据的个数并输入一组数"<<endl;
cin>>i;
for (j=0;j<i;j++)
{
cin>>m;
creat1(m);
}
}
void link::creat1(int num)
{
node *q=rear;
rear=new node;
rear->next=NULL;
rear->data=num;
q->next=rear;
size++;
}
bool link::search(int i)
{
if (i>size)
return 0;
else {
int j;
node *r=first;
for (j=0;j<i;j++)
first=first->next;
cout<<first->data;
first=r;
return 1;
}
}
bool link::insert(int i,int number)
{
if (i>size)
return 0;
else if (i==1)
{
node *p=new node;
p->data=number;
node *q=first->next;
p->next=q;
first->next=p;
size++;
return 1;
}
else{
node *r=first;
int j;
for (j=0;j<i-1;j++)
first=first->next;
node *p=new node;
p->data=number;
node *q=first->next;
p->next=q;
first->next=p;
size++;
first=r;
return 1;
}
}
bool link::shanchu(int i,int &x)
{
if (size==0||i>size) //如果删除节点的位置大于链表的长度,出错
return 0;
else if (i==size) //如果删除的是最后一个节点
{
node *r=first;
int j;
for (j=0;j<i-1;j++)
first=first->next;
x=first->next ->data;
delete first->next;
rear=first;
rear->next=NULL;
first=r;
size--;
return 1;
}
else{
node *r=first;
int j;
for (j=0;j<i-1;j++)
first=first->next;
x=first->next->data;
node *m=first->next->next;
delete first->next;
first->next =m;
first=r;
size--;
return 1;
}
}
void link::output(node *f)
{
f=f->next;
while (f)
{
cout<<f->data<<" ";
f=f->next;
}
cout<<endl;
}

int main()
{
link l1,l2;
cout<<"创建第一个链表为"<<endl;
l1.creat();
cout<<"创建的链表元素为"<<endl;
l1.output(l1.first);
l1.insert(2,18);
cout<<"插入之后的链表元素为"<<endl;
l1.output(l1.first);
int k;
l1.shanchu(2,k);
cout<<"删除之后的链表元素为"<<endl;
l1.output(l1.first);
cout<<"删除元素为"<<k<<endl;
return 0;
}追问

原题是“实现链表节点的增加、删除、查找、以及链表数据的输出操作” 我记错了啊
帮帮忙在改改吧(我刚学c++不会弄啊),谢谢啊 我会再给你加分的

追答

我写好了,把你邮箱地址给我吧,我发你邮箱。

追问

[email protected]

温馨提示:答案为网友推荐,仅供参考
第1个回答  2012-06-25
山科大的吧,同学。本回答被提问者采纳
相似回答