写在前面:
教材:数据结构(C语言版) 严蔚敏 吴伟民 编著 清华大学出版社
实验跟随教材编写的顺序
实验一 线性表
实验目的:
理解线性表的创建、插入和删除操作;掌握顺序表的定义、插入和删除操作时对数据元素的移动。
实验内容:
1. 通过结构体声明顺序存储的线性表;
2. 在初始化操作中,对上述线性表分配存储空间,如可容纳100个元素;
3. 编写插入元素的操作;
4. 编写输出元素的操作;
5. 在主函数中声明一个顺序存储的线性表,通过不断插入新元素,构建保存元素的线性表;依次输出各元素,验证线性表结构的正确性。
实验要求 :1. 对重要语句进行备注,以表明对程序的正确理解。
源码:
首先将以后所要用到的宏和头文件写在VS的stdafx.h文件中。
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//
#pragma once
//#include "targetver.h"
#include <stdio.h>
#include <tchar.h>
#include <cstdlib>
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define OVERFLOW -2
#define LIST_INIT_SIZE 100
#define LISTINCREMENT 10
// TODO: reference additional headers your program requires here
#include <iostream>
#include "stdafx.h"
using namespace std;
typedef int Status;
typedef int ElemType;
//定义一个SqList结构体
typedef struct{
ElemType *elem;
int length;
int listsize;
}SqList;
//初始化函数
Status InitList_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;
return OK;
}
//插入函数,添加报错机制
Status ListInert_Sq(SqList& L, int i, ElemType e){
if (i < 1 || i > L.length + 1)
return ERROR;
if (L.length >= L.listsize)
{
ElemType *newbase = (ElemType *)realloc(L.elem, (L.listsize + LISTINCREMENT) * sizeof(ElemType));
if (!newbase)
exit(OVERFLOW);
L.elem = newbase;
L.listsize += LISTINCREMENT;
}
ElemType *p, *q;
q = &(L.elem[i-1]);
for(ElemType* p = &(L.elem[L.length - 1]); p >= q; --p){
*(p + 1) = *(p);
}
*q = e;
++L.length;
return OK;
}
//主函数
int main()
{
int i;
SqList L1;
InitList_Sq(L1);
//调用Inert函数顺序插入10个数
for(i = 1; i <= 10; i++){
ListInert_Sq(L1, i, i * 2);
}
//显示2到20
cout << "The total numbers are:" << endl;
for(i = 0; i < 10; i++){
cout << L1.elem[i] << " ";
//printf("%d ", L1.elem[i]);
}
cout << endl;
InitList_Sq(L1);
//调用Inert函数逆序插入10个数
for(i = 1; i <= 10; i++){
ListInert_Sq(L1, 1, i * 2);
}
//显示20到2
cout << "The total numbers are:" << endl;
for(i = 0; i < 10; i++){
cout << L1.elem[i] << " ";
}
cout << endl;
return 0;
}
由于是第一个实验,所以代码还是比较少的,具体注释已经写在上面代码中了。
运行结果: