解题思路:
注意事项:
参考代码:#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node* next;
};
class link{
public:
link(){front = new node;front->data = -1;front->next = nullptr;};
link(int data[],int len);
void Get(int pos);
void Delete(int pos);
void Insert(int pos,int val);
void show();
private:
node* front;
};
link::link(int data[],int len){
front = new node;
front->next = nullptr;
for(int i = 0; i< len; i++)
{
node* s = new node;
s->data = data[i];
s->next = front;
front = s;
}
};
void link::Get(int pos)
{
if(front->next == nullptr)
{
printf("get fail\n");
return;
}
node* s = front;
int p = 1;
while(s->next != nullptr)
{
if(p == pos)
{
printf("%d\n",s->data);
}
p++;
s = s->next;
}
printf("get fail\n");
}
void link::Delete(int pos){
if(front->next == nullptr)
{
printf("delete fail\n");
return;
}
node* pre = front;
if(pos == 1)
{
front = pre->next;
delete pre;
printf("delete OK\n");
return;
}
int p = 1;
while(pre->next != nullptr)
{
if(p == pos-1)
{
node* cur = pre->next;
pre->next = cur->next;
delete cur;
printf("delete OK\n");
return;
}
p++;
pre = pre->next;
}
printf("delete fail\n");
}
void link::Insert(int pos, int val) {
if(front->next == nullptr && pos != 1)
{
printf("insert fail\n");
return;
}
if(pos == 1)
{
node *s = new node;
s -> next = front;
s->data = val;
front = s;
printf("insert OK\n");
return;
}
node* pre = front;
int p = 1;
while(pre->next != nullptr)
{
if(p == pos-1)
{
node* cur = new node;
cur->data = val;
cur->next = pre->next;
pre->next = cur;
printf("insert OK\n");
return;
}
p++;
pre = pre->next;
}
printf("insert fail\n");
}
void link::show(){
if(front->next == nullptr)
{
printf("Link list is empty\n");
return;
}
node* s = front;
while(s->next)
{
printf("%d ",s->data);
s = s->next;
}
printf("\n");
}
int main(){
int n,s[100010];
scanf("%d",&n);
if(n == 0)
{
printf("Link list is empty\n");
return 0;
}
for(int i = 0; i< n; i++)
{
scanf("%d",&s[i]);
}
int m;
scanf("%d",&m);
class link Link(s,n);
while(m--)
{
string str;
int val,pos;
cin >> str;
cin.ignore();
if(str == "show")
{
Link.show();
}
else if(str == "get")
{
scanf("%d",&pos);
Link.Get(pos);
}
else if(str == "insert")
{
scanf("%d%d",&pos,&val);
Link.Insert(pos,val);
}
else if(str == "delete")
{
scanf("%d",&pos);
Link.Delete(pos);
}
}
return 0;
}
0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复