天天看点

【小练习】顺序表的就地逆置1.练习代码2关键点分析

文章目录

  • 1.练习代码
  • 2关键点分析
    • 2.1题目要求
    • 2.2题目分析
    • 2.3代码走读
    • 2.4运行结果

1.练习代码

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
typedef struct
{
	int * base;
	int length;
}sqlist;

void reverseSQ(sqlist *list)
{
	int low = 0, high = list->length - 1;
	int buf, i;
	for (i=0; i<(list->length)/2; i++)
	{
		buf = list->base[low];
		list->base[low] = list->base[high];
		list->base[high] = buf;
		low++;
		high--;
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	sqlist list;
	const int Maxsize = 10;
	int a, i=0;
	list.base = (int *)malloc(sizeof(int)*Maxsize);
	list.length = 0;

	printf("Please input below 10 integer into the sqlist:\n");
	printf("Type -1 for stopping input\n");
	scanf("%d", &a);
	while(a != -1 && i<=9)
	{
		list.base[i] = a;
		list.length++;
		i++;
		scanf("%d", &a);
	}

	printf("The contents of the sqlist are\n");
	for (i=0; i<list.length; i++)
		printf("%d ", list.base[i]);
	printf("\n");

	reverseSQ(&list);

	printf("The contents of the reversed sqlist are\n");
	for (i=0; i<list.length; i++)
		printf("%d ", list.base[i]);
	printf("\n");

	return 0;
}
                

2关键点分析

2.1题目要求

编写一个函数,实现顺序表的就地逆置,也就是说利用原表的存储空间将顺序表(a1, a2, …, an)逆置为(an, an-1, …, a1)。

2.2题目分析

要实现长度为length的顺序表的就地逆置,需要利用一个临时变量buf作为数据的缓冲区,同时要设置两个指针变量low和high分别指向顺序表的首尾。

步骤1:将low指向内容放入buf

步骤2:将high指向内容放入low

步骤3:将buf内容放入high

步骤4:low++,high–

步骤5:重复执行1-4步length/2次

2.3代码走读

#include "stdafx.h"
#include <stdio.h>
#include <iostream>
//定义一个顺序表类型
typedef struct
{
	int * base;
	int length;
}sqlist;

//顺序表就地逆置函数
void reverseSQ(sqlist *list)
{
	int low = 0, high = list->length - 1; //指针分别指向首尾
	int buf, i; //临时缓冲区buf,及循环变量i
	for (i=0; i<(list->length)/2; i++) //循环执行length/2次
	{
		buf = list->base[low]; //将low指向内容放入buf
		list->base[low] = list->base[high]; //将high指向内容放入low
		list->base[high] = buf; //将buf内容放入high
		low++; //首指针后移1位
		high--; //尾指针前移1位
	}
}

int _tmain(int argc, _TCHAR* argv[])
{
	sqlist list;
	const int Maxsize = 10;
	int a, i=0;
	list.base = (int *)malloc(sizeof(int)*Maxsize);
	list.length = 0;

	printf("Please input below 10 integer into the sqlist:\n");
	printf("Type -1 for stopping input\n");
	scanf("%d", &a);
	while(a != -1 && i<=9)
	{
		list.base[i] = a;
		list.length++;
		i++;
		scanf("%d", &a);
	}

	printf("The contents of the sqlist are\n");
	for (i=0; i<list.length; i++)
		printf("%d ", list.base[i]);
	printf("\n");

	reverseSQ(&list);

	printf("The contents of the reversed sqlist are\n");
	for (i=0; i<list.length; i++)
		printf("%d ", list.base[i]);
	printf("\n");

	return 0;
}
                

2.4运行结果

【小练习】顺序表的就地逆置1.练习代码2关键点分析

继续阅读