用一个转置函数实现原地颠倒线性表元素的顺序
编写函数ArrayList::reverse,不创建新的数组进行转置。
颠倒顺序前,线性表的第i个元素是element[i-1], 颠倒后变为element[listSize-i-1]。
可以分别使用数组和指针两种方式实现转置。
实现reverse函数相关代码
(1)通过数组实现转置的方法:
定义一个临时变量temp,将element[i]赋值给temp,再将element[listSize-i-1],最后将temp赋值给element[listSize-i-1]即可。
temp=element[i];
element[i]=element[listSize-1-i];
element[listSize-1-i]=temp;
以下代码使用了类模板,只实现了reverse()函数,但我给出了linearList.h和arrayList.h的全部函数声明,其余函数的实现代码可以自行查书或上网。
linearList.h的函数声明:
#ifndef SRC_LINEARLIST_H_
#define SRC_LINEARLIST_H_
#include <iostream>
template <typename T>
class linearList {
public:
virtual ~linearList(){};
virtual bool empty() const = 0;
virtual int size() const = 0;
virtual T& get(int theIndex) const = 0;
virtual int indexOf(const T& theElement) const = 0;
virtual void erase(int theIndex) = 0;
virtual void insert(int theIndex, const T& theElement) = 0;
virtual void output(std::ostream& out) const = 0;
virtual void reverse()const=0; //定义一个纯虚函数
};
继承类数组线性表arrayList.h的函数声明:
#ifndef SRC_ARRAYLIST_H_
#define SRC_ARRAYLIST_H_
#include "linearList.h"
template <typename T>
class arrayList :public linearList<T> {
public:
explicit arrayList(int initialCapacity = 10);
~arrayList(){delete [] element;}
arrayList(const arrayList&);
arrayList<T>& operator=(const arrayList<T>& rhs);
bool empty() const {return listSize == 0;}
int size() const {return listSize;}
T& get(int theIndex) const;
int indexOf(const T& theElement) const;
void erase(int theIndex);
void insert(int theIndex, const T& theElement);
void output(std::ostream& out) const;
int capacity() const {return arrayLength;}
void changeLength1D(T* & source, int oldLength, int newLength);
void copy(const T* start, const T* end, T* target)const;
void copy_backward(const T * start, const T* end, T* tartget)const;
const T * find( const T* start, const T* end, const T &theElement) const;
void reverse()const; //实现转置的函数
protected:
void checkIndex(int theIndex) const;
T* element;//存储线性表的一维数组
int arrayLength;// 容量
int listSize;//线性表的元素个数
继承类数组线性表arrayList.cpp的函数声明(只实现了reverse()函数):
template <class T>
void arrayList<T>::reverse()const
{
T temp;
for(int i=0;i<(listSize/2);i++)
{
temp=element[i];
element[i]=element[listSize-1-i];
element[listSize-1-i]=temp;
}
}
(2)通过指针实现转置的方法:
定义两个指针分别指向线性表储存的第一个元素之前和最后一个元素之后,需要注意element其实是一个指针。再定义一个T类型的临时变量temp用于交换元素。
T* begin = element-1;
T* end=element+listSize;
T temp;
分别使其自增和自减,使用循环比较两个指针大小并通过temp交换两个指针指向的元素。
while(++begin<–end)
{
temp=*begin;
*begin=*end;
*end=temp;
}
以下是完整代码,因为linearList.h和arrayList.h的函数声明和上述用数组方法实现的代码相同。所以这里只给出arrayList.cpp中reverse()函数的代码:
template <class T>
void arrayList<T>::reverse()
{
T* begin = element-1;
T* end=element+listSize;
T temp;
while(++begin<--end)
{
temp=*begin;
*begin=*end;
*end=temp;
}
}