题目描述
链表是数据结构中一种最基本的数据结构,它是用链式存储结构实现的线性表。它较顺序表而言在插入和删除时不必移动其后的元素。现在给你一些整数,然后会频繁地插入和删除其中的某些元素,会在其中某些时候让你查找某个元素或者输出当前链表中所有的元素。
下面给你基本的算法描述:
图1:链表类型的定义以及获得链表元素的算法描述
图2:链表的插入算法描述
图3:链表的删除算法描述
图4:链表的创建算法描述
输入格式
输入数据只有一组,第一行有n+1个整数,第一个整数是这行余下的整数数目n,后面是n个整数。这一行整数是用来初始化列表的,并且输入的顺序与列表中的顺序相反,也就是说如果列表中是1、2、3那么输入的顺序是3、2、1。
第二行有一个整数m,代表下面还有m行。每行有一个字符串,字符串是“get”,“insert”,“delete”,“show”中的一种。如果是“get”或者“delete”,则其后跟着一个整数a,代表获得或者删除第a个元素;如果是“insert”,则其后跟着两个整数a和e,代表在第a个位置前面插入e;“show”之后没有整数。
输出
如果获取成功,则输出该元素;如果删除成功则输出“delete OK”;如果获取失败或者删除失败,则输出“get fail”以及“delete fail”。如果插入成功则输出“insert OK”,否则输出“insert fail”。如果是“show”则输出列表中的所有元素,如果列表是空的,则输出“Link list is empty”。注:所有的双引号均不输出。
样例输入
3 3 2 1
21
show
delete 1
show
delete 2
show
delete 1
show
delete 2
insert 2 5
show
insert 1 5
show
insert 1 7
show
insert 2 5
show
insert 3 6
show
insert 1 8
show
get 2
样例输出
1 2 3
delete OK
2 3
delete OK
2
delete OK
Link list is empty
delete fail
insert fail
Link list is empty
insert OK
5
insert OK
7 5
insert OK
7 5 5
insert OK
7 5 6 5
insert OK
8 7 5 6 5
7
#include<iostream>
#include<string.h>
#include<malloc.h> /* malloc()等 */
#include<stdio.h> /* EOF(=^Z或F6),NULL */
#include<stdlib.h> /* atoi() */
#include<math.h>
using namespace std;
#define ERROR 0;
#define OK 1;
typedef int Status;
typedef int ElemType;
typedef struct Lnode
{
ElemType date;
struct Lnode *next;
}Lnode,*LinList;
Status Getdate (LinList L,int i)
{
LinList q;
int j=1;
q=L->next;
while(q&&j<i)
{
q=q->next;
j++;
}
if(j>i||!q)
return ERROR;
return q->date;
}
Status InsertLin (LinList L,int i,ElemType e)
{
int j=0;
LinList q,p;
q=L;
while(q&&j<i-1)
{
q=q->next;
j++;
}
if(!q||j>i-1)
return ERROR;
p=(LinList)malloc(sizeof(Lnode));
p->date=e;
p->next=q->next;
q->next=p;
return OK;
}
Status DeleteLin (LinList L,int i)
{
int j=0;
LinList q,p;
q=L;
while(q->next&&j<i-1)
{
q=q->next;
j++;
}
if(!(q->next)||j>i-1)
return ERROR;
p=q->next;
q->next=p->next;
free(p);
return OK;
}
Status ShowList(LinList L)
{
LinList q;
int k=0;
q=L->next;
while(q)
{
if(k==1)
cout<<' ';
k=1;
cout<<q->date;
q=q->next;
}
if(k==0)
{
return ERROR;
}
else
{
cout<<endl;
return OK;
}
}
void CreateList(LinList *L,int n)
{
LinList q;
int i;
(*L)=(LinList)malloc(sizeof(Lnode));
(*L)->next=NULL;
for(i=0;i<n;i++)
{
q=(LinList)malloc(sizeof(Lnode));
cin>>q->date;
q->next=(*L)->next;
(*L)->next=q;
}
}
int main()
{
int n,m,i,Date,t,e;
char str[30];
cin>>n;
LinList L;
CreateList(&L,n);
cin>>m;
while(m--)
{
cin>>str;
if(strcmp(str,"get")==0)
{
cin>>i;
Date=Getdate(L,i);
if(Date)
cout<<Date<<endl;
else
cout<<"get fail"<<endl;
}
else if(strcmp(str,"delete")==0)
{
cin>>i;
t=DeleteLin(L,i);
if(t)
cout<<"delete OK"<<endl;
else
cout<<"delete fail"<<endl;
}
else if(strcmp(str,"show")==0)
{
t=ShowList(L);
if(!t)
cout<<"Link list is empty"<<endl;
}
else if(strcmp(str,"insert")==0)
{
cin>>i>>e;
t=InsertLin(L,i,e);
if(t)
cout<<"insert OK"<<endl;
else
cout<<"insert fail"<<endl;
}
}
}