順序表創建和就地逆置
本題要求實現順序表的創建和就地逆置操作函數。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
Answer
C++版本
Status ListCreate_Sq(SqList &L) {
L.elem = (ElemType*)malloc(sizeof(ElemType)*LIST_INIT_SIZE);
if(!L.elem)
exit(OVERFLOW);
L.length = 0;
L.listsize = LIST_INIT_SIZE;
int num;
scanf("%d",&num);
if(num <= 0)
return ERROR;
while(num--){
int number;
scanf("%d",&number);
L.elem[L.length++] = number;
}
return OK;
};
void ListReverse_Sq(SqList &L) {
int p = L.length/2;
if(L.length % 2 != 0){
for(int i = 0,j = L.length-1;i < p,j > p;i++,j--){
ElemType t;
t = L.elem[i];
L.elem[i] = L.elem[j];
L.elem[j] = t;
}
}else{
for(int i = 0,j = L.length-1;i < j;i++,j--){
ElemType t;
t = L.elem[i];
L.elem[i] = L.elem[j];
L.elem[j] = t;
}
}
};
C版本
Status ListCreate_Sq(SqList *L) {
L->elem = (ElemType*)malloc(sizeof(ElemType)*LIST_INIT_SIZE);
if(!L->elem)
exit(OVERFLOW);
L->length = 0;
L->listsize = LIST_INIT_SIZE;
int num;
scanf("%d",&num);
if(num <= 0)
return ERROR;
while(num--){
int number;
scanf("%d",&number);
L->elem[L->length++] = number;
}
return OK;
};
void ListReverse_Sq(SqList *L) {
int p = L->length/2;
if(L->length % 2 != 0){
for(int i = 0,j = L->length-1;i < p,j > p;i++,j--){
ElemType t;
t = L->elem[i];
L->elem[i] = L->elem[j];
L->elem[j] = t;
}
}else{
for(int i = 0,j = L->length-1;i < j;i++,j--){
ElemType t;
t = L->elem[i];
L->elem[i] = L->elem[j];
L->elem[j] = t;
}
}
};