6-1 順序表創建和就地逆置(10 分)
本題要求實現順序表的創建和就地逆置操作函數。L是一個順序表,函數ListCreate_Sq(SqList &L)用於創建一個順序表,函數ListReverse_Sq(SqList &L)是在不引入輔助數組的前提下將順序表中的元素進行逆置,如原順序表元素依次爲1,2,3,4,則逆置後爲4,3,2,1。
函數接口定義:
Status ListCreate_Sq(SqList &L);
void ListReverse_Sq(SqList &L);
裁判測試程序樣例:
//庫函數頭文件包含
#include<stdio.h>
#include<malloc.h>
#include<stdlib.h>
//函數狀態碼定義
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
typedef int Status;
//順序表的存儲結構定義
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
typedef int ElemType; //假設線性表中的元素均爲整型
typedef struct{
ElemType* elem; //存儲空間基地址
int length; //表中元素的個數
int listsize; //表容量大小
}SqList; //順序表類型定義
Status ListCreate_Sq(SqList &L);
void ListReverse_Sq(SqList &L);
int main() {
SqList L;
ElemType *p;
if(ListCreate_Sq(L)!= OK) {
printf("ListCreate_Sq: 創建失敗!!!\n");
return -1;
}
ListReverse_Sq(L);
if(L.length){
for(p=L.elem;p<L.elem+L.length-1;++p){
printf("%d ",*p);
}
printf("%d",*p);
}
return 0;
}
/* 請在這裏填寫答案 */
輸入格式: 第一行輸入一個整數n,表示順序表中元素個數,接下來n個整數爲表元素,中間用空格隔開。 輸出格式: 輸出逆置後順序表的各個元素,兩個元素之間用空格隔開,最後一個元素後面沒有空格。
輸入樣例:
4
1 2 3 4
輸出樣例:
4 3 2 1
Status ListCreate_Sq(SqList &L)
{
L.elem=(ElemType*)malloc(LIST_INIT_SIZE*sizeof(ElemType));
//創建單鏈表並分配內存
if(!L.elem)
exit(OVERFLOW);
L.length=0;
L.listsize=LIST_INIT_SIZE;//分配單鏈表最大容量
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",L.elem+i);
L.length++;//寫入數據,長度加加
}
return OK;
}
void ListReverse_Sq(SqList &L)
{
ElemType temp;
for(int i=0;i<L.length/2;i++)//頭尾交換三部曲
{
temp=*(L.elem+i);
*(L.elem+i)=*(L.elem+L.length-i-1);
*(L.elem+L.length-i-1)=temp;
}
}