单链表(结构)
题目描述
单链表结点的存储结构SNode包含两部分:数据、下一结点指针。单链表首个结点的地址head为表头指针,定义SNode *head=NULL表示单链表初始为空。
单链表的创建:createList(SNode *&head, int *value, int n),用value数组中的n个数据生成一个单链表(表头指针为head)。
单链表的输出:printList(SNode *head),从头至尾遍历以head为表头的单链表,输出每个结点的数据值。
单链表数据插入: insertNode(SNode *head, int pos, int value),在单链表第pos(1<=pos<=L+1)个结点位置插入新结点,数据为value。若插入不成功,输出error。
单链表数据删除: removeNode(SNode *head, int pos), 删除单链表第pos(1<=pos<=L)个结点。若删除不成功,输出error。
单链表的撤销:deleteList(SNode *head),删除以head为表头的单链表,即释放链表每个结点的堆内存。
注:不可以用任何形式的数组来实现链表,否则不计成绩。
输入
第一行:测试次数t
对每组测试数据,格式如下:
数据个数n 数据1 数据2 数据3 … 数据n
插入次数m
插入位置1 数据1
…
插入位置m 数据m
删除次数o
删除位置1
…
删除位置o
输出
对每组测试数据:
输出创建链表后链表中全部结点的数据
对每组插入测试数据:
输出插入操作后链表中全部结点的数据
对每组删除测试数据:
输出删除操作后链表中全部结点的数据
示例输入
2
5 2 3 5 7 3
2
2 40
8 60
2
7
3
6 1 2 10 0 1 5
2
2 40
8 60
2
1
3
示例输出
2 3 5 7 3
2 40 3 5 7 3
error
error
2 40 5 7 3
1 2 10 0 1 5
1 40 2 10 0 1 5
1 40 2 10 0 1 5 60
40 2 10 0 1 5 60
40 2 0 1 5 60
记住创建了新链表要在程序结束前把链表删去
#include<iostream>
using namespace std;
struct SNode
{
int data;
SNode *next;
};
void createList(SNode *&head, int *value, int n);
void printList(SNode *head);
int insertNode(SNode *head, int pos, int value);
int removeNode(SNode *head, int pos);
void deleteList(SNode *head);
int main()
{
int i,t,m,n;
cin>>t;
for(i=0;i<t;i++)
{
SNode *head=NULL;
head=new SNode;
head->data=1;
head->next=NULL;
cin>>n;
int *val=new int [n];
for(m=0;m<n;m++)
cin>>val[m];
createList(head,val,n);
printList(head);
int in,j;
cin>>in;
if(in<0)
cout<<"error "<<endl;
for(j=0;j<in;j++)
{
int pos,value,d;
cin>>pos>>value;
d=insertNode(head,pos,value);
if(d==0)
cout<<"error"<<endl;
else
printList(head);
}
int out,j2;
cin>>out;
if(out<0)
cout<<"error"<<endl;
for(j2=0;j2<out;j2++)
{
int pos,d;
cin>>pos;
d=removeNode(head,pos);
if(d==0)
cout<<"error"<<endl;
else
printList(head);
}
deleteList(head);
delete []val;
}
return 0;
}
void createList(SNode *&head, int *value, int n)
{
int m;
SNode *tail=head;
for(m=0;m<n;m++)
{
SNode *p=new SNode;
p->data=*(value+m);
p->next=NULL;
tail->next=p;
tail=p;
head->data++;
}
}
void printList(SNode *head)
{
SNode *tail;
int j;
tail=head;
for(j=1;j<=head->data+1;j++)
{
if(tail->next)
{
tail=tail->next;
cout<<tail->data;
if(j!=head->data-1)
cout<<" ";
}
}
cout<<endl;
}
int insertNode(SNode *head,int pos,int value)
{
int i;
if(pos<1||pos>=head->data+1)
return 0;
SNode *p=new SNode;
p->data=value;
SNode *q=head;
for(i=1;i<pos;i++)
{
q=q->next;
}
p->next=q->next;
q->next=p;
head->data++;
return 1;
}
int removeNode(SNode *head, int pos)
{
SNode *q=head;
if(pos>0&&pos<head->data)
{
for(int i=1;i<pos;i++)
q=q->next;
SNode *p=q->next;
q->next=p->next;
head->data--;
return 1;
}
else
return 0;
}
void deleteList(SNode *head)
{
SNode *p;
while(head->next)
{
p=head->next;
head->next=p->next;
delete p;
}
delete head;
}