版权声明:原创文章,转载请注明出处 https://blog.csdn.net/hza419763578/article/details/88539188
问题 A: 算法2-8~2-11:链表的基本操作
输入
输入数据只有一组,第一行有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>
using namespace std;
struct Node
{
int data;
Node* next;//Node* 不是int了
};
Node* L=NULL;
int op1,op2;
Node* create(int Array[],int n){
//不要傻傻Node* p,pre,head ★★★
Node *p,*pre,*head;//要头结点 否则链表元素删光了,咋办
head=new Node;
pre=NULL;
head->next=pre;
for(int i=0;i<n;i++){
p=new Node;
p->data=Array[i];
p->next=pre;
pre=p;
head->next=pre;
}
return head;
}
//获取第a个元素
void get(int a){
Node* p=L;
for(int i=0;i<a&&p!=NULL;i++){
p=p->next;
}
if(p!=NULL){
cout<<p->data<<endl;
}else{
cout<<"get fail"<<endl;
}
}
//删除第a个元素
void del(int a){
Node* p=L;
for(int i=0;i<a-1&&p!=NULL;i++){
p=p->next;
}
if(p!=NULL&&p->next!=NULL){//找到前一个元素
Node* q=p->next;
p->next=q->next;
delete(q);
cout<<"delete OK"<<endl;
}else{
cout<<"delete fail"<<endl;
}
}
//插入
void insert(int pos,int e){
Node* p=L;
for(int i=0;i<pos-1&&p!=NULL;i++){
p=p->next;
}
if(p!=NULL){//找到前一个元素 可以插n+1 个 不然空时(n=0)还插不进去了
Node* q=new Node;
q->data=e;
q->next=p->next;
p->next=q;
cout<<"insert OK"<<endl;
}else{
cout<<"insert fail"<<endl;
}
}
//show
void printL(){
Node* p=L;
if(p->next==NULL){
cout<<"Link list is empty";
}else{
for(p=L->next;p!=NULL;p=p->next){
if(p->next==NULL){
cout<<p->data;
}else{
cout<<p->data<<" ";
}
}
}
cout<<endl;
}
void optation(string str){
if(str=="show"){
printL();
}else if(str=="delete"){
cin>>op1;
del(op1);
}else if(str=="insert"){
cin>>op1>>op2;
insert(op1,op2);
}else if(str=="get"){
cin>>op1;
get(op1);
}else{
cout<<"筛选出错!!!\n";
}
}
int main(){
// freopen("input.txt","r",stdin);
int N,Array[100000];
while(cin>>N){
for(int i=0;i<N;i++){
cin>>Array[i];
}
L=create(Array,N);
int T;
string s;
cin>>T;
while(T--){
cin>>s;
optation(s);
}
}
return 0;
}