顺序表相关操作 (一)

2014-11-24 03:04:33 · 作者: · 浏览: 7
[cpp]
// SequenceList.h: interface for the CSequenceList class.
//
//////////////////////////////////////////////////////////////////////

#if !defined(AFX_SEQUENCELIST_H__ECAED4FD_189E_4994_9843_BC7E9134CAF8__INCLUDED_)
#define AFX_SEQUENCELIST_H__ECAED4FD_189E_4994_9843_BC7E9134CAF8__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define MAXSIZE 100
#define LIST_INIT_SIZE 100
#define LIST_INCREMENT 100
typedef int DataType;

typedef struct
{
DataType *data;
int iLength;
int iAllocatedSpace;
}SqList;

class CSequenceList
{
public:
SqList sqList;
CSequenceList();
virtual ~CSequenceList();
void operator = (const CSequenceList listSeq)
{
sqList.data = listSeq.sqList.data;
sqList.iLength = listSeq.sqList.iLength;
sqList.iAllocatedSpace = listSeq.sqList.iAllocatedSpace;
}
BOOL InitList();
BOOL Insert(int index, DataType elem);
BOOL Delete(int index);
DataType GetAt(int index);
BOOL DestroyList();
BOOL IsEmpty();
int GetLength();
int Find(int from, DataType& elem);
void Unique();
CSequenceList MergeList(CSequenceList& listA);
void Reverse();
};

#endif // !defined(AFX_SEQUENCELIST_H__ECAED4FD_189E_4994_9843_BC7E9134CAF8__INCLUDED_)



// SequenceList.cpp: implementation of the CSequenceList class.
//
//////////////////////////////////////////////////////////////////////

#include "stdafx.h"
#include "DataStruct.h"
#include "SequenceList.h"

#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CSequenceList::CSequenceList()
{

}

CSequenceList::~CSequenceList()
{

}

/************************************************************************
函数名: InitList
作 者: 谭友亮(Charles Tan)
日 期: 2013-4-12
作 用: 初始化顺序表,为为顺序表动态分配空间
形参数:
返回值: 成功:true 失败: false
************************************************************************/
BOOL CSequenceList::InitList()
{
sqList.data = (DataType*)malloc(LIST_INIT_SIZE * sizeof(DataType));
//sqList.data = new DataType[LIST_INIT_SIZE];
if (sqList.data == NULL)
{
return false;
}
sqList.iLength = 0;
sqList.iAllocatedSpace = LIST_INIT_SIZE;

return true;
}

/************************************************************************
函数名: Insert
作 者: 谭友亮(Charles Tan)
日 期: 2013-4-12
作 用: 往顺序表中index之前插入插入元素
形参数: index 从0开始的索引
elem 要插入的元素
返回值: 成功:true 失败: false
************************************************************************/
BOOL CSequenceList::Insert(int index, DataType elem)
{
int i;
DataType *newBase;

if (index < 0 || index > sqList.iLength)
{
return false;
}

if (sqList.iLength >= sqList.iAllocatedSpace)
{
newBase = (DataType*)realloc(sqList.