//線性表的通用程序,c語言實現
#include <stdio.h>
#include <stdlib.h>
#define MaxSize 50
typedef char DataType;
typedef struct node
{
DataType data[MaxSize]; int last;
}Lnode,*List;
//初始化線性表
void Init_List(List L)
{
L->last = 0;
}
//線性表的長度
int Length_List(List L)
{
return L->last;
}
//取表中元素
DataType Get_List(List L, int i, DataType x)
{
if (i<1 || i>L->last)
printf("error!!!");
else
x = L->data[i-1]; return x;
}
//查找表L中值為x的元素,其結果返回在表L中首次出現的值為x元素的序號或地址
DataType Location_List(List L, DataType x)
{
int i = 0;
while (i < L->last && L->data[i] != x)
i++;
if (i == L->last)
return -1;
else
return (i + 1);
}
//在線性表的第i個位置插入值為x人元素
void Insert_List(List L, int i, DataType x)
{
int j;
if (i<1 || i>L->last + 1)
printf("插入位置錯!!!\n");
else
{
for (j = L->last; j >= i; j--)
L->data[j] = L->data[j - 1];
L->data[i - 1] = x;
}
L->last++;
}
//刪除線性表第i個位置上的元素
void Delete_List(List L, int i)
{
int j;
if (i<1 || i>L->last)
printf("del error");
else
{
for (j = i; j < L->last; j++)
L->data[j - 1] = L->data[j];
L->last--;
}
}
//輸出線性表
void Print_List(List L)
{
int i;
for (i = 1; i < L->last; i++)
printf("%c->",L->data[i-1]);
printf("%c",L->data[L->last-1]);
}
///////////////主函數////////////////
void main()
{
int i = 1, n;
Lnode L;
char ch, x;
Init_List(&L);
printf("\n\n\n***************線性表演示程序****************\n");
printf("請輸入您想建立的線性表的元素,以#結束:");
ch = getchar();
while (ch != '#')
{
Insert_List(&L,i,ch);
i++;
ch = getchar();
}
printf("你建立的線性表為:");
Print_List(&L);
printf("\n線性表的長度為:%d",L.last);
//fflush(stdin);
printf("\n輸入你想查找的元素:");
fflush(stdin);
scanf("%c",&x);
printf("你查找的元素為%c序位為%d\n",x,Location_List(&L,x));
printf("輸入你想查找的元素序位:");
scanf("%d",&n);
printf("\n你查找的元素為:%c\n",Get_List(&L,n,x));
printf("輸入你想插入的元素以及序位:<用逗號隔開>");
fflush(stdin);
scanf("%c,%d",&x,&n);
Insert_List(&L,n,x);
printf("\n插入后的線性表為:\n");
Print_List(&L);
fflush(stdin);
printf("\n請輸入你想刪除的元素序位:");
scanf("%d",&n);
Delete_List(&L,n);
printf("\n刪除后的線性表為:\n");
Print_List(&L);
printf("\n");
system("pause");
}
運行結果: