顺序表
#include <stdio.h>
#define MaxSize 50
typedef struct
{
int data[MaxSize];
int length;
}SqList;
bool ListInsert(SqList *L, int i, int key);
bool ListDelete(SqList *L, int i, int *key);
int ListLocate(SqList *L, int key);
void Reverse(SqList *L);
bool Merge(SqList L1, SqList L2, SqList *L3);
int main()
{
SqList L;
L.length = 0;
for(int i = 0; i < 10; i++)
{
ListInsert(&L, i+1, i);
}
for(int i = 0; i < L.length; i++)
{
printf("%-5d", L.data[i]);
}
printf("LENGTH: %-10d\n", L.length);
int key = NULL;
ListDelete(&L, 5, &key);
for(int i = 0; i < L.length; i++)
{
printf("%-5d", L.data[i]);
}
printf("LENGTH: %-10d", L.length);
printf("KEY: %-10d\n", key);
int LocateKey = ListLocate(&L, 3);
if(LocateKey)
printf("The location of key: %d\n", LocateKey);
else
printf("no key in the SqList!\n");
Reverse(&L);
for(int i = 0; i < L.length; i++)
{
printf("%-5d", L.data[i]);
}
printf("LENGTH: %-10d\n", L.length);
SqList L1,L2,L3;
L1.length = L2.length = L3.length = 0;
for(int i = 0; i < 10; i++)
{
ListInsert(&L1, i+1, i+1);
ListInsert(&L2, i+1, i+2);
}
for(int i = 0; i < L1.length; i++)
{
printf("%-5d", L1.data[i]);
}
printf("LENGTH of 1: %-10d\n", L1.length);
for(int i = 0; i < L2.length; i++)
{
printf("%-5d", L2.data[i]);
}
printf("LENGTH of 2: %-10d\n", L2.length);
Merge(L1, L2, &L3);
for(int i = 0; i < L3.length; i++)
{
printf("%-5d", L3.data[i]);
}
printf("LENGTH of 3: %-10d\n", L3.length);
return 0;
}
bool ListInsert(SqList *L, int i, int key)
{
if(i < 0 || i >= MaxSize || L->length == MaxSize)
return false;
for(int j = L->length-1; j >= i; j--)
{
L->data[j] = L->data[j-1];
}
L->data[i-1] = key;
L->length++;
return true;
}
bool ListDelete(SqList *L, int i, int *key)
{
if(i < 0 || i >= MaxSize || L->length == MaxSize)
return false;
*key = L->data[i-1];
for(int j = i-1; j < L->length-1; j++)
{
L->data[j] = L->data[j+1];
}
L->length--;
return false;
}
int ListLocate(SqList *L, int key)
{
for(int i = 0; i < L->length; i++)
{
if(L->data[i] == key)
{
return i+1;
}
}
return 0;
}
void Reverse(SqList *L)
{
for(int i = 0; i < L->length/2; i++)
{
int temp = L->data[i];
L->data[i] = L->data[L->length-1 - i];
L->data[L->length - i] = temp;
}
}
bool Merge(SqList L1, SqList L2, SqList *L3)
{
if(L1.length+L2.length > MaxSize)
return false;
int i1 = 0, i2 = 0, r = 0;
while(i1 < L1.length && i2 < L2.length)
{
if(L1.data[i1] <= L2.data[i2])
{
L3->data[r] = L1.data[i1];
r++;
i1++;
L3->length++;
}
else
{
L3->data[r] = L2.data[i2];
r++;
i2++;
L3->length++;
}
}
while(i1 < L1.length)
{
L3->data[r++] = L1.data[i1++];
L3->length++;
}
while(i2 < L2.length)
{
L3->data[r++] = L2.data[i2++];
L3->length++;
}
return true;
}