p17 5无序表中删除值在s和t之间元素(包括s和t)
c
#include<stdio.h>
#include<stdlib.h>
#define MaxSize 100
typedef struct {
int* data;
int capacity;
int length;
}SeqList;
int InitList(SeqList &L) {
L.data = (int*)malloc(MaxSize * sizeof(int));
L.capacity = MaxSize;
L.length = 0;
return 1;
}
int CreateList(SeqList &L, int n) {
int i;
for (i = 0; i < n; i++) {
scanf_s("%d", &L.data[i]);
}
L.length = n;
return 1;
}
int ListDelete(SeqList& L,int i,int &e) {
if (i > L.length || i < 0) {
return 0;
}
e = L.data[i - 1];
for (int j= i; j<L.length; j++) {
L.data[j - 1] = L.data[j];
}
L.length--;
}
int ListInsert(SeqList &L, int i, int e) {
if (i > L.length+1 || i < 0) {
return 0;
}
for (int j = L.length; j >= i; j--) {
L.data[j] = L.data[j - 1];
}
L.data[i - 1] = e;
L.length++;
return 1;
}
int LocateElem(SeqList& L, int e) {
for (int i = 0; i < L.length; i++) {
if (L.data[i] == e) {
return i + 1;
}
}
}
void PrintList(SeqList L) {
for (int i = 0; i < L.length; i++) {
printf("%d ", L.data[i]);
}
printf("\n");
}
int DeleteMin(SeqList &L) {
int m = 100000, locate;
for (int i = 0; i < L.length; i++) {
if (L.data[i] < m) {
m = L.data[i];
locate = i;
}
}
printf("%d %d\n",m, locate);
L.data[locate] = L.data[L.length-1];
return m;
}
void Deletefrom(SeqList &L,int s,int t) {
if (s > t || s<0 || t>L.length - 1)
exit(-1);
int c = t - s;
for (int i = t; i <L.length; i++) {
L.data[i - c] = L.data[i];
}
L.length = L.length- c-1;
}
//有序表,所以找到第一个大于t的元素下标,第一个大于等于s的元素下标
void DeleteBetween(SeqList& L, int s, int t) {
if (s >= t ||L.length==0)
exit(-1);
int i, j;
for (i=0;i<L.length&&L.data[i] < s; i++);
for (j=i; j < L.length && L.data[j] <= t; j++);
for (; j< L.length; j++,i++) {
L.data[i] = L.data[j];
}
L.length = i;
}
//无序表
void Del_s_t(SeqList& L,int s,int t) {//删除顺序表中值在s和t之间的元素,用k记录值在s和t中元素的个数
int k = 0;
for (int i = 0; i < L.length; i++) {
if (L.data[i] >= s && L.data[i] <= t) {
k++;
}
else {
L.data[i - k] = L.data[i];
}
}
L.length = L.length - k;
}
int main() {
int n;
scanf_s("%d", &n);
SeqList L;
InitList(L);
CreateList(L,n);
PrintList(L);
int s, t;
scanf_s("%d%d", &s, &t);
Del_s_t(L, s, t);
PrintList(L);
return 0;
}