問題 C: 順序表基本運算(線性表)
時間限制: 1 Sec??內存限制: 128 MBDescription
編寫一個程序,實現順序表的各種基本運算(假設順序表的元素類型為char),主函數已給出,請補充每一種方法。
?
1、初始化順序表L;
2、采用尾插法依次插入元素a,b,c,d,e;
3、輸出順序表L;
4、輸出順序表L的長度;
5、判斷順序表是否為空;
6、輸出順序表L的第三個元素;
7、輸出元素a的位置;
8、在第四個元素位置插入元素f;
9、輸出順序表L;
10、刪除L的第三個元素;
11、輸出順序表L;
12、釋放順序表L;
? ??
數據元素類型定義為
typedef char ElemType;
?
順序表的定義為
typedef struct
{
? ? ElemType data[SizeMax];
? ? int length;
} SqList;
??
?
主函數:
int main()
{
? ? SqList *L;
? ? InitList(L); ? ? ? ? ? ? ? ? ? ? ? ? ? ?//初始化順序表
? ? ElemType a,b,c,d,e;
? ? scanf("%c %c %c %c %c%*c",&a,&b,&c,&d,&e);
? ? Insert(L,a);
? ? Insert(L,b);
? ? Insert(L,c);
? ? Insert(L,d);
? ? Insert(L,e); ? ? ? ? ? ? ? ? ? ? ? ? ? ?//使用尾插法插入元素a,b,c,d,e
? ? Print(L); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //輸出順序表
? ? PrintLength(L); ? ? ? ? ? ? ? ? ? ? ? ? //輸出順序表長度
? ? if(SqNull(L))
? ? ? ? ?printf("順序表不為空\n");
? ? else printf("順序表為空\n"); ? ? ? ? ? ?//判斷順序表是否為空
? ? PrintData(L,3); ? ? ? ? ? ? ? ? ? ? ? ? //輸出第三個元素
? ? printf("元素a的位置:%d\n",Find(L,a)); ?//輸出元素a的位置
? ? ElemType f;
? ? scanf("%c",&f);
? ? Insertinto(L,4,f); ? ? ? ? ? ? ? ? ? ? ?//將f插入到第四個位置
? ? Print(L); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //輸出順序表
? ? Delete(L,3); ? ? ? ? ? ? ? ? ? ? ? ? ? ?//刪除第三個元素
? ? Print(L); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? //輸出順序表
? ? free(L); ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ?//釋放內存
? ? return 0;
}
Input
第一行輸入五個元素a,b,c,d,e;接下來輸入元素f;請根據題目編寫算法。
Output
Sample Input
1 2 3 4 5
6
Sample Output
1 2 3 4 5
5
順序表不為空
3
元素a的位置:1
1 2 3 6 4 5
1 2 6 4 5
提示
請使用C++編譯并提交
#include <stdio.h>
#include <stdlib.h>
#define SizeMax 10
typedef char ElemType;
typedef struct
{ElemType data[SizeMax];int length;
} SqList;
void InitList(SqList *&L)
{L=(SqList*)malloc(sizeof(SqList));L->length=0;
}
void Insert(SqList *&L,ElemType n)
{L->data[L->length]=n;L->length++;
}
void Print(SqList *&L)
{int i;for(i=0;i<L->length-1;i++){printf("%c ",L->data[i]);}printf("%c\n",L->data[i]);
}
void PrintLength(SqList *&L)
{printf("%d\n",L->length);
}
bool SqNull(SqList *&L)
{if(L->length)return 1;return 0;
}
void PrintData(SqList *L,int n)
{if(L->length<n)return;printf("%c\n",L->data[n-1]);
}
int Find(SqList *L,ElemType a)
{for(int i=0;i<L->length;i++)if(L->data[i]==a)return i+1;return 0;
}
void Insertinto(SqList *&L,int n,ElemType f)
{for(int i=L->length;i>=n;i--)L->data[i]=L->data[i-1];L->data[n-1]=f;L->length++;
}
void Delete(SqList *&L,int n)
{for(int i=n-1;i<L->length;i++)L->data[i]=L->data[i+1];L->length--;
}
int main()
{SqList *L;InitList(L); //初始化順序表ElemType a,b,c,d,e;scanf("%c %c %c %c %c%*c",&a,&b,&c,&d,&e);Insert(L,a);Insert(L,b);Insert(L,c);Insert(L,d);Insert(L,e); //使用尾插法插入元素a,b,c,d,ePrint(L); //輸出順序表PrintLength(L); //輸出順序表長度if(SqNull(L))printf("順序表不為空\n");else printf("順序表為空\n"); //判斷順序表是否為空PrintData(L,3); //輸出第三個元素printf("元素a的位置:%d\n",Find(L,a)); //輸出元素a的位置ElemType f;scanf("%c",&f);Insertinto(L,4,f); //將f插入到第四個位置Print(L); //輸出順序表Delete(L,3); //刪除第三個元素Print(L); //輸出順序表free(L); //釋放內存return 0;
}