题目
实现单链表的创建(分头部插入、尾部插入)、链表元素查找、删除、插入、输出各个元素,最后实现链表的翻转。(例:原链表为1->2->3->4 要求结果输出:4->3->2->1)
测试代码(部分)
void rel()
{
node<t> *p;
node<t> *s;
p=first->next;
s=p->next;
first->next=NULL;
while(p!=NULL)
{
p->next=first->next;
first->next=p;
p=s;
//cout<<"1"<<endl;
if(p!=NULL)
{ s=p->next;
}
}
}
linklist(){first=new node<t>;}
linklist(t x){first=new node<t>(x);}
void creat(t end)
{
node<t> * newnode;
t val;
cin>>val;
while(val!=end)
{
newnode= new node<t>(val);
newnode->next=first->next;
first->next=newnode;
cin>>val;
}
}
void creat1(t end)
{
node<t> * r;
node<t> * s;
r=first;
t val;
cin>>val;
while(val!=end)
{
s=new node<t>(val);
r->next=s;
r=s;
cin>>val;
}
//first=new node<t>
r->next=NULL;
}
void print()
{
node<t> * p=first->next;
while(p!=NULL)
{
cout<<p->data<<"--->>";
p=p->next;
}
cout<<"NULL"<<endl;
}
int length()
{
node<t> *p;
p=first->next;
int count=0;
while(p!=NULL)
{
p=p->next;
count++;
}
return count;
}
t get(int i)
{
node<t> * p;
int count=1;
p=first->next;
while(p!=NULL&&count<i)
{
p=p->next;
count++;
}
if(p==NULL) throw"位置";
else
return p->data;
}
void insert(t x, int i)
{
node<t> * p;
node<t> *s;
p=first;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL) throw "位置";
else
{
s=new node<t>(x);
s->next=p->next;
p->next=s;
}
}
int locate(t x)
{
node<t> *p;
p=first->next;
int count=1;
while(p!=NULL)
{
if(p->data==x)
return count;
p=p->next;
count++;
}
return 0;
}
void del(int i)
{
node<t> *p;
node<t> *q;
p=first;
int count=0;
while(p!=NULL&&count<i-1)
{
p=p->next;
count++;
}
if(p==NULL||p->next==NULL)
throw "位置";
else
{
q=p->next;
p->next=q->next;
delete q;
}
}
~linklist()
{
node<t> *p;
while(first!=NULL)
{
p=first;
first=first->next;
delete p;
}
}
程序运行界面
项目完整源代码
有需要项目源代码的小伙伴
可以在海轰的微信公众号:海轰Pro
回复:海轰
就可以啦(注意看使用说明哦o( ̄︶ ̄)o)