数组操作C

数组操作

Description
给你一个长度为 n 的数组,并给出如下几种操作:

在下标为 a 的位置插入一个整数 b,如果其后有元素,则全部后移。例如,数组为 1, 2, 3,在下标为 1 的位置插入 4,则数组变为:1, 4, 2, 3。
删除下标为 a 的元素,如果其后有元素,则全部前移。例如,数组为 1, 2, 3,删除下标为 0 的元素,则数组变为:2, 3。
修改下标为 a 的元素的值为 b。
输出整个数组。
Input
输入数据有多组(数据组数不超过 10),到 EOF 结束。

对于每组数据:

首先输入一行 n, m (1 <= n <= 10^6, 1 <= m <= 10^4),分别表示初始数组的长度和操作次数。
接下来一行输入 n 个用空格隔开的整数 Ai (0 <= Ai <= 1000),表示初始的数组。
最后有 m 行,每行对应一次操作,根据操作类型分为不同的输入格式(具体含义参见描述部分,0 <= a, b <= 1000):
1 a b
2 a
3 a b
4
Output
对于每组数据中的每次类型为 4 的操作,输出一行,表示此时的数组,每个整数之间用空格隔开。

Samples
Sample #1
Input
3 6
1 2 3
1 1 4
4
2 2
4
3 2 8
4
Output
1 4 2 3
1 4 3
1 4 8

分析:

对于链表简单的插入、删除、修改、打印输出

#include <bits/stdc++.h>
using namespace std;
typedef struct node{
	int data;
	struct node *next;
}s;
struct node *creat(int n){
	s *head,*tail,*p;
	int a;
	head=(struct node *)malloc (sizeof(struct node));
	tail=head;
	tail->next=NULL;
	for(int i=0;i<n;i++){
		cin>>a;
		p=(struct node *)malloc (sizeof(struct node));
		p->data=a;
		tail->next=p;
		tail=p;
		tail->next=NULL;
	}
	return head;
};
struct node *insert(s *head,int a,int b){
	s *p,*r,*q;
	p=head->next;
	q=head;
	int t=0;
	while(p&&t<a){
		p=p->next;
		q=q->next;
		t++;
	}
	r=(struct node *)malloc (sizeof(struct node));
	r->data=b;
	if(p==NULL){//到末尾了 
		p->next=r;
		r->next=NULL; 
	}
	else{
		r->next=p;
		q->next=r;
	}
	return head;    
};
s *delet(s *head,int a){
	s *p,*r,*q;
	p=head->next;
	q=head;
	int t=0;
	while(p->next!=NULL&&t<a){
		p=p->next;
		q=q->next;
		t++;
	}
	if(p->next==NULL&&t==a){
		q->next=NULL;
	}
	else if(t==a&&p->next!=NULL){
		q->next=p->next;
	}
	free(p);
	return head;
};
struct node *change(s *head,int a,int b){
	s *p,*r,*q;
	p=head->next;
	q=head;
	int t=0;
	while(p&&t<a){
		p=p->next;
		q=q->next;
		t++;
	}
	if(p!=NULL){ 
		p->data=b;
	}
	return head;    
};
void printout(s *head){
	s *p;
	p=head->next;
	while(p){
		cout<<p->data<<" ";
		p=p->next;
	}
	cout<<endl;
}
int n,m,x,a,b,k=0;
int main(){
	while(cin>>n>>m){
        s *head,*p,*q,*r,*t;
        head=creat(n);
        for(int i=0;i<m;i++){
    	cin>>x;
    	if(x==1){
    		cin>>a>>b;
    		head=insert(head,a,b);
		}
    	if(x==2){
    		cin>>a;
    		head=delet(head,a);
		}
		if(x==3){
			cin>>a>>b;
			head=change(head,a,b);
		}
		if(x==4){
			printout(head);
		}
	}	
	}
    
    return 0;
}
  • 10
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值