[Data Structure Exercise] Interval Deletion (PTA) of Linear Table Elements

Require:

Given a sequentially stored linear table, design a function to remove all elements whose value is greater than min and less than max. After deletion, the remaining elements in the table are stored in order, and the relative position cannot be changed.

Function interface definition:

List Delete( List L, ElementType minD, ElementType maxD );

where the Liststructure is defined as follows:

typedef int Position;
typedef struct LNode *List;
struct LNode {
    
    
    ElementType Data[MAXSIZE];
    Position Last; /* 保存线性表中最后一个元素的位置 */
};

LIt is a linear table passed in by the user, in which ElementTypeelements can be compared by >, ==, <; minDand maxDthe lower and upper bounds of the value range of the element to be deleted, respectively. The function Deleteshould delete Data[]all the elements whose values ​​are greater than minDand less than maxDthat in the table, and at the same time ensure that the remaining elements in the table are stored in order, and the relative position remains unchanged, and finally returns the table after deletion.

Example of the referee test procedure:

#include <stdio.h>

#define MAXSIZE 20
typedef int ElementType;

typedef int Position;
typedef struct LNode *List;
struct LNode {
    
    
    ElementType Data[MAXSIZE];
    Position Last; /* 保存线性表中最后一个元素的位置 */
};

List ReadInput(); /* 裁判实现,细节不表。元素从下标0开始存储 */
void PrintList( List L ); /* 裁判实现,细节不表 */
List Delete( List L, ElementType minD, ElementType maxD );

int main()
{
    
    
    List L;
    ElementType minD, maxD;
    int i;

    L = ReadInput();
    scanf("%d %d", &minD, &maxD);
    L = Delete( L, minD, maxD );
    PrintList( L );

    return 0;
}

/* 你的代码将被嵌在这里 */

Input sample:

10
4 -8 2 12 1 5 9 3 3 10
0 4

Sample output:

4 -8 12 5 9 10 

code

Only now did I realize that I can do function problems without worrying about the implementation of functions other than the requirements. I wasted a lot of time on this before, and it is much easier to submit function functions directly, which is stupid. . .

/*
 * @Description : 删除区间元素
 * @param  -L   : 需要删除的链表
 * @param -minD : 下边界
 * @param -maxD : 上边界
 * @return 		: 删除后的元素
 */
List Delete( List L, ElementType minD, ElementType maxD )
{
    
    
    int n = 0;
    for (int i = 0; i <= L->Last; i++){
    
    
        if (L->Data[i] > minD && L->Data[i] < maxD){
    
    
            //得出需要删除的个数
            n++;
        }
        else{
    
    
            //非区间内的保持,区间内的删除
            L->Data[i - n] = L->Data[i];
        }
    }
    L->Last = L->Last - n;
    return L;
}

Guess you like

Origin blog.csdn.net/qq_45628620/article/details/114804338