回复 8楼 纵横阳仔
程序代码:
#include <stdio.h>
#define MAX 20
typedef struct __struct_node
{
size_t length;
int data[MAX];
} String;
void display(String *ss)
{
printf("String:\n");
for (size_t i = 0; i < ss->length; ++i)
{
printf("%d ", ss->data[i]);
}
printf("\n");
}
void insert(String *ss, size_t pos, int data)
{
if (pos < 0) return;
if (ss->length == MAX) return;
for (size_t i = ss->length; i > pos; --i)
{
ss->data[i] = ss->data[i - 1];
}
ss->length += 1;
ss->data[pos] = data;
}
void insertBefore(String *ss, int beforeItem, int data)
{
for (size_t i = 0; i < ss->length; ++i)
{
if (beforeItem == ss->data[i])
{
insert(ss, i, data);
i += 1;
}
}
}
void insertBefore2(String *ss, int beforeItem, int data)
{
size_t count = 0;
for (size_t i = 0; i < ss->length; ++i) count += beforeItem == ss->data[i];
if (ss->length + count > MAX) return;
ss->length += count;
for (size_t i = ss->length - 1; count; --i)
{
ss->data[i] = ss->data[i - count];
if (beforeItem == ss->data[i])
{
count -= 1;
ss->data[--i] = data;
}
}
}
int main(void)
{
String ss = {.data={1, 3, 4, 4, 5, 6}, .length = 6};
display(&ss);
insertBefore(&ss, 4, 7);
display(&ss);
insertBefore(&ss, 4, 4);
display(&ss);
insertBefore2(&ss, 4, 7);
display(&ss);
insertBefore2(&ss, 4, 4);
display(&ss);
return 0;
}