Mid-term review of data structure --- Chapter 1 introduction --- program fragments

Chapter One Introduction

1. Cycle left

void reverseArr(int A[],int start,int rear)
{
    
    
    for(int i=start,j=rear;i<=(start+rear)/2;i++,j++)
    {
    
    
        int temp=A[i];
        A[i]=A[j];
        A[j]=temp;
    }
}

2. Odd and even number arrangement

Idea: Set the working pointers i and j respectively, i point to the low address end of the array, and j points to the high address end of the array. Once it is found that the left is an even number and the right is an odd number, a swap occurs.

void split(int A[],int n)
{
    
    
    forint i=0,j=n-1;i<j;i++,j--)
    {
    
        //前奇后偶,正常i++,j--
        if(A[i]%2==0 && A[j]%2==1)   //前偶后奇,交换位置
        {
    
    
            int temp=A[i];
            A[i]=A[j];
            A[j]=temp;
        }
        else if(A[i]%2==0 && A[j]%2==0) i--;    //前偶后偶,i继续停留在原来位置,不能让i后移
        else if(A[i]%2==1 && A[j]%2==1) j++;    //前奇后奇,j继续停留在原来位置,不能让j前移
    }
}

3. Palindrome skewer

#include <iostream>
using namespace std;
bool judge(string str)
{
    
    
    int n=str.length();
    for(int i=0;i<n/2;i++)
    {
    
    
        if(str[i]==str[n-1]) n--;    //从前往后,从后往前,一起遍历
        else return false;
    }
    retrun true;
}
int main()
{
    
    
    string s;
    getline(cin,s);
    bool res=judge(s);
    if(res) cout<<"YES"<<endl;
    else cout<<"NO"<<endl;
    return 0;
}

4. Find the maximum and second largest value

#include <iostram>
using namespace std;
void getmax(int A[],int n,int &fmax,int &smax)
{
    
    
    fmax=0;
    smax=0;
    for(int i=0;i<n;i++)
    {
    
    
        if(fmax<A[i])
        {
    
    
            smax=fmax;
            fmax=A[i];
        }
        else if(smax<A[i])    //else if语句里,fmax>=A[i]
        {
    
    
            smax=A[i];
        }
    }

}
int main()
{
    
    
    int n,maxV,nMax;
    cin>>n;
    int a[n];
    for(int i=0;i<n;i++)
    {
    
    
        cin>>a[i];
    }
    getMax(a,n,maxV,nMax);
    cout<<maxV<<" "<<nMax<<endl;
    return 0;
}

Guess you like

Origin blog.csdn.net/Fantasycometrue/article/details/109584652