C语言实验——数组逆序

这篇博客介绍了一个C语言程序,用于实现数组中指定范围内的元素逆序。通过创建和操作栈来完成交换过程,包括栈的初始化、进栈、出栈等操作。示例展示了如何对输入的数组进行特定位置的元素交换并打印结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

有n个整数,使其最后m个数变成最前面的m个数,其他各数顺序向后移m(m < n < 100)个位置。

输入

输入数据有2行,第一行的第一个数为n,后面是n个整数,第二行整数m。

输出

按先后顺序输出n个整数。

示例输入

5 1 2 3 4 5
2

示例输出

4 5 1 2 3


#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
using namespace std;
const int  maxsize = 10000;


typedef int elemtype;
typedef struct Stack
{
    int Size;
    elemtype *top,*base;
} Stack;


bool Empty(Stack &s)//判断是否为空栈;
{
    if (s.top == s.base)
    {
        return 1;
    }
    return 0;
}


void Creat(Stack &s)//栈的初始化;
{
    s.base=new elemtype[maxsize];///
    s.top=s.base;
//    s.top++;
//    s.base++;
    s.Size=maxsize;
}


void push(Stack &s,elemtype e)//进栈;
{
    if (s.top-s.base >= s.Size)
    {
        s.base=(elemtype *)realloc(s.base,2*maxsize*sizeof(Stack));
        s.Size+=maxsize;
        ///s.top=s.base+s.Size;
    }
    s.top++;
    *s.top=e;
}


void pop(Stack &s)//出栈
{
    if (s.top != s.base)
    {
        s.top--;
    }
}


void print(Stack &s)//栈内所有元素的输出;
{
    while (!Empty(s))
    {
        cout<<*s.top;
        pop(s);
    }
    cout<<endl;
}
void Clear(Stack &s)//清空栈;
{
    while (!Empty(s))
    {
        pop(s);
    }
}


void exch(Stack &s,int a[],int m,int n)//数组前每m个元素和过后m个元素互换位置;
{
    int i;
    for (i=n; i>n-m; i--)
    {
        push(s,a[i]);
    }
    while(!Empty(s))
    {
        cout<<*s.top<<" ";
        s.top--;
    }
    for (i=n-m; i>=1; i--)
    {
        push(s,a[i]);
    }
    while(!Empty(s))
    {
        cout<<*s.top;
        s.top--;
        if (!Empty(s))
        {
            cout<<" ";
        }
    }
    cout<<endl;
}
int main()
{
    int a[1000];
    int m,i,n;
    Stack s;
    Creat(s);
    cin>>n;
    for (i=1; i<=n; i++)
    {
        cin>>a[i];
    }
    cin>>m;
    exch(s,a,m,n);//数组前每m个元素和过后m个元素互换位置;
    print(s);
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值