chap2 7-1 jmu-ds-順序表區間元素刪除 (15 分)

若一個線性表L採用順序存儲結構存儲,其中所有的元素爲整數。設計一個算法,刪除元素值在[x,y]之間的所有元素,要求算法的時間複雜度爲O(n),空間複雜度爲O(1)。

輸入格式:

三行數據,第一行是順序表的元素個數,第二行是順序表的元素,第三行是x和y。

輸出格式:

刪除元素值在[x,y]之間的所有元素後的順序表。

輸入樣例:

10
5 1 9 10 67 12 8 33 6 2
3 10

輸出樣例:

1 67 12 33 2

#include<stdio.h>
#include<stdlib.h>
#include <iostream>
using namespace std;
#define LIST_INIT_SIZE 1000
typedef int ElemType;
typedef struct
{
    ElemType *elem;
    int length;
    int listsize;
}SqList;
void  InitList_Sq(SqList &L)
{
    L.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType));
    L.length = 0;
}
void Change_Sq(SqList &L,int x,int y)
{
    int i;
    for(i = 0; i<L.length ;i=i)
    {
        if(L.elem[i]>=x&&L.elem[i]<=y)
        {
            int p;
            for(p = i;p < L.length - 1;p++)
            {
                L.elem[p] = L.elem[p+1];
            }
            L.length--;
        }
        else
            i++;
    }
}
int main()
{
    SqList L;
    InitList_Sq(L);
    int m,i,x,y;
    cin>>m;
    for(i=0;i<m;i++)
    {
        cin>>L.elem[i];
        L.length++;
    }
    cin>>x>>y;
    Change_Sq(L,x,y);
    for(i=0;i < L.length - 1 ; i++)
    {
        cout<<L.elem[i]<<" ";
    }
    cout<<L.elem[L.length-1]<<"\n";
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章