reverse all elements of the sequence list

#include<stdio.h>
#include <stdlib.h>
#include <iostream>
using namespace std;
constexpr auto Maxsize = 10;
typedef struct {
    
    
	int  *data;
	int length;
}SqList;

//初始化顺序表(动态分配)
void InitSqList(SqList &L) {
    
    
L.data = (int*)malloc(sizeof(int)* Maxsize);
if (L.data == NULL) {
    
    

	printf("分配内存失败");
}
else {
    
    
int i;
L.length = Maxsize;
for (i = 0; i < Maxsize; i++) {
    
    
	L.data[i] = i;
	printf("%d\n", L.data[i]);
}
}
}
//顺序表逆置
bool ListReverse(SqList& L) {
    
    
	int i, j;
	int b[Maxsize];
	for (i = 0, j = Maxsize - 1; i < Maxsize && j >= 0; ) {
    
    
		b[j--] = L.data[i++];
	}
	for (i = 0, j = 0; j < Maxsize && i < Maxsize; j++) {
    
    
		L.data[i] = b[j];
		printf("%d\n", L.data[i]);
	}

	return  true;
};//空间复杂度为O(n)

/*
bool ListReverse(SqList& L, int a) {
	int i, j;

	for (i = 0; i < Maxsize / 2; i++, --a) {
		j = L.data[i];
		L.data[i] = L.data[a];
		L.data[a] = j;
	}
	for (i = 0; i < Maxsize; i++) {
		printf("%d\n", L.data[i]);
	}
	return  true;
};
*/空间复杂度为O(1)
//主函数
int main() {
    
    
	SqList L;
	InitSqList(L);
	ListReverse(L);
	return 0;
}


Analysis: There are doubts about the time complexity of O(n) :
1. The data defined by the sequence table structure is obviously a pointer. Why is the following code directly used as an array?
2. Because arrays cannot be used as lvalues, do we still need to allocate space when using static allocation (int data[MaxSize];)?
No, static allocation means specifying the size of the space when defining the sequence table.
Part of the code should be changed to:

typedef struct {
    
    
	int  data[MaxSize];
	int length;
}SqList;

//初始化顺序表(动态分配)
void InitSqList(SqList &L) {
    
    
//L.data = new int[Maxsize];
	L.length = Maxsize;
}

Guess you like

Origin blog.csdn.net/weixin_44195690/article/details/119140503