原题链接:数据结构-链表的基本操作
解题思路:一点一点测试,一点一点来
注意事项:慢慢把思路理清就行
参考代码:
#include <iostream>
#include <algorithm>
#include <string>
#include <cstring>
using namespace std;
struct node
{
int data;
node* next;
};
int x,y,n,m;
string s;
//创建链表
node* create(int n)
{
node *head,*p;
head=new node;
head->next=NULL;
while(n--){
cin>>x;
p=new node;
p->data=x;
p->next=head->next;
head->next=p;
}
return head;
}
//展示链表各元素的值
void show(node* head)
{
int flag=0;
node* p=head;
p=p->next;
if(p==NULL){
cout<<"Link list is empty"<<endl;
return ;
}
while(p!=NULL){
//flag=1;
cout<<p->data<<" ";
p=p->next;
}
cout<<endl;
}
//删除第t个结点
int del(node* head,int t)
{
if(t<=0) return 0;
int flag=0;
node* p=head;
node* q;
//p=p->next;
int cnt=1;
while(p!=NULL){
if(cnt==t){
q=p->next;
p->next=q->next;
flag=1;
break;
}else{
p=p->next;
//t--;
cnt++;
}
}
return flag;
}
//在第pos个位置添加值为value的结点
int insert(node* head,int pos,int value)
{
if(pos<=0) return 0;
int flag=0;
node* p=head;
node* q;
//p=p->next;
int cnt=1;
while(p!=NULL){
if(cnt==pos){
q=new node;
q->data=value;
q->next=p->next;
p->next=q;
flag=1;
break;
}else{
p=p->next;
//t--;
cnt++;
}
}
return flag;
}
//获取第t个结点的值
int get(node* head,int t)
{
if(t<=0) return 0;
int flag=0;
node* p=head;
node* q;
p=p->next;
int cnt=1;
while(p!=NULL){
if(cnt==t){
return p->data;
//flag=1;
//break;
}else{
p=p->next;
//t--;
cnt++;
}
}
return flag;
}
void test()
{
int a[5]={1,2,3,4,5};
node* head=create(5);
show(head);
cout<<del(head,3)<<endl;
show(head);
cout<<insert(head,1,1000)<<endl;
show(head);
cout<<insert(head,2,555)<<endl;
show(head);
cout<<get(head,1)<<endl;
show(head);
}
int main()
{
while(cin>>n){
node* head=create(n);
//show(head);
cin>>m;
while(m--){
cin>>s;
if(s[0]=='s'){
show(head);
//else cout<<"Link list is empty"<<endl;
//show(head);
}else if(s[0]=='d'){
cin>>x;
if(del(head,x)){
cout<<"delete OK"<<endl;
}else{
cout<<"delete fail"<<endl;
}
}else if(s[0]=='i'){
cin>>x>>y;
if(insert(head,x,y)){
cout<<"insert OK"<<endl;
}else{
cout<<"insert fail"<<endl;
}
}else if(s[0]=='g'){
cin>>x;
if(get(head,x)){
cout<<get(head,x)<<endl;
}else{
cout<<"get fail"<<endl;
}
}
}
}
return 0;
}0.0分
0 人评分
C语言网提供由在职研发工程师或ACM蓝桥杯竞赛优秀选手录制的视频教程,并配有习题和答疑,点击了解:
一点编程也不会写的:零基础C语言学练课程
解决困扰你多年的C语言疑难杂症特性的C语言进阶课程
从零到写出一个爬虫的Python编程课程
只会语法写不出代码?手把手带你写100个编程真题的编程百练课程
信息学奥赛或C++选手的 必学C++课程
蓝桥杯ACM、信息学奥赛的必学课程:算法竞赛课入门课程
手把手讲解近五年真题的蓝桥杯辅导课程
发表评论 取消回复