版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
定义单链表类,创建带头结点的单链表(节点类型为整型数据),要求包含以下成员函数:
头插法创建单链表(利用构造函数实现)
尾插法创建单链表(重载构造函数实现)
链表的遍历
按值删除一个节点
按位置删除一个节点
链表的析构
输入
输入一组数据,以尾插法的形式创建单链表(0表示输入结束)(构造第一个链表)
输入一组数据,以头插法的形式创建单链表(0表示输入结束)(构造第二个链表)
输入要删除元素的值(在尾插法创建的链表中进行改操作)
输入要删除元素的位置(在尾插法创建的链表中进行改操作)
输出
输出尾插法创建链表的结果
输出头插法插法创建链表的结果
输出按值删除之后链表中剩余的元素(若删除的元素不存在,输出Error)
输出按位置删除之后链表中剩余的元素(若删除的元素不存在,输出Error
样例输入
1 2 3 4 5 0
1 2 3 4 5 0
2
0
样例输出
1 2 3 4 5
5 4 3 2 1
1 3 4 5
Error
AC代码:
#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
const int maxn=10000;
template<class T>
struct node
{
int data;
node<T>* next;
};
template<class T>
class lian
{
node<T> *first;
public:
lian();
lian(T a[],int n);
lian(T a[],int n,int m);
//~lian();
void show();
void zhishan(T n);
void weishan(int n);
};
template <class T>
lian<T>::lian()
{
first=new node<T>;
first->next=NULL;
}
template <class T>
lian<T>::lian(T a[],int n)
{
first=new node<T>;
first->next=NULL;
for(int i=0;i<n;i++)
{
node<T> *s=NULL;
s=new node<T>;
s->data=a[i];
s->next=first->next;
first->next=s;
}
}
template <class T>
lian<T>::lian(T a[],int n,int m)
{
first=new node<T>;
node<T> *r=first;
//first=new node<T>;
//first->next=NULL;
r=first;
node<T> *s=NULL;
for(int i=0;i<n;i++)
{
s=new node<T>;
s->data=a[i];
r->next=s;
r=s;
}
r->next=NULL;
}
template <class T>
void lian<T>::show()
{
node<T> *p;
p=first->next;
while(p!=NULL)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
template <class T>
void lian<T>::zhishan(T n)
{
node<T> *p=first,*q=NULL;
T x;
int t=0;
while(p->next!=NULL)
{
if(p->next->data==n)
{
q=p->next;x=q->data;
p->next=q->next;
delete q;
t++;
continue;
}
p=p->next;
}
if(t==0)
cout<<"Error"<<endl;
else
show();
}
template <class T>
void lian<T>::weishan(int n)
{
if(n<1)
{
cout<<"Error"<<endl;
return;
}
node<T> *p=first,*q=NULL;
int c=0;
while(p!=NULL&&c<n-1)
{
p=p->next;
c++;
}
if(p==NULL||p->next==NULL)
{
cout<<"Error"<<endl;
return;
}
else
{
q=p->next;
p->next=q->next;
delete q;
show();
return;
}
}
int main()
{
int a[maxn],b[maxn];
int x,y;
int n=0;
while(1)
{
cin>>a[n];
if(a[n]==0)break;
n++;
}
lian<int> h(a,n,1);
h.show();
n=0;
while(1)
{
cin>>a[n];
if(a[n]==0)break;
n++;
}
lian<int> k(a,n);
k.show();
cin>>x;
h.zhishan(x);
cin>>y;
h.weishan(y);
}