缺點:
根本原因:靜態存儲的分配
1.插入和刪除都需要移動大量的元素,等概率情況下,平均要移動一半的元素。
2.表的容量難以確定,數組的長度必須事先確定
3.造成存儲空間的碎片。數組要求佔用連續的存儲空間,即使存儲單元數超過所需的數目,如不連續沒辦法使用。
優點:
1.具有簡單、運算方便等優點
2.適用於小線性表或長度固定的線性表,採用順序存儲結構的優越性更爲突出。
頭文件:
#if !defined(AFX_SEQLIST_H__E40EA55C_049B_4830_A87D_5C6A9A777B84__INCLUDED_)
#define AFX_SEQLIST_H__E40EA55C_049B_4830_A87D_5C6A9A777B84__INCLUDED_
#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000
#include <iostream>
using namespace std;
const int MaxSize = 100; //示例數據,可以根據實際問題具體定義
template <class DataType> //定義模板類 CSeqList
class CSeqList
{
public:
CSeqList(){length = 0;}; //無參構造函數,建立一個空的順序表
virtual ~CSeqList();
CSeqList(DataType a[], int n); //有參構造函數,建立一個長度爲N的順序表
int Length() {return length;}; //返回順序表的長度
DataType Get(int i); //按位查找,在線性表中查找第I個元素
int Locate(DataType x); //按值查找,在線性表中查找值位X的元素序號
void Insert(int i, DataType x); //插入操作,在線性表的第I個位置插入值x
DataType Delete(int i); //刪除操作,刪除線性表第I個元素
void ModifyList(int i, DataType x); //修改線性表中,第I個元素的值爲x
void PrintList(); //遍歷操作,按序號依次輸出各元素
private:
DataType data[MaxSize]; //存放數據元素的數組
int length; //線性表的長度
};
#endif // !defined(AFX_SEQLIST_H__E40EA55C_049B_4830_A87D_5C6A9A777B84__INCLUDED_)
#include "SeqList.h"
//建立一個長度爲N的順序表
template <class DataType>
CSeqList<DataType>::CSeqList(DataType a[], int n)
{
if (n > MaxSize)
throw "非法參數";
for (int i = 0; i < n; i++)
data[i] = a[i];
length = n;
}
//按位查找,在線性表中查找第I個元素
template <class DataType>
DataType CSeqList<DataType>::Get(int i)
{
if (i < 1 || i > length) throw "查找非法位置";
else return data[i - 1];
}
//按值查找,在線性表中查找值位X的元素序號
//平均時間性能O(n)
template <class DataType>
int CSeqList<DataType>::Locate(DataType x)
{
for (int i = 0; i < length; i++)
if (data[i] == x) return i+1; //返回其序號i+1
return 0;
}
//插入操作,在線性表的第I個位置插入值x
//必須從最後一個元素開始移動,直至將第I個元素後移爲止。然後將新元素插入。
//i = len+1 表尾插入 O(1);
//i = 1 表頭插入 O(n)
// 等概率情況下,平均要移動一半的元素 平均時間複雜度O(n)
template <class DataType>
void CSeqList<DataType>::Insert(int i, DataType x)
{
if (length >= MaxSize) throw "上溢出";
if (i < 1 || i > length+1) throw "位置錯誤";
for (int j = length; j >= i; j--)
data[j] = data[j-1]; //注意第J個元素數組下標爲j-1
data[i-1] = x;
length++;
}
//刪除操作,刪除線性表第I個元素
//必須從 i+1個元素開始前移。
template <class DataType>
DataType CSeqList<DataType>::Delete(int i)
{
if (length == 0) throw "下溢出";
if (i < 1 || i > length+1) throw "位置錯誤";
int x = data[i - 1];
for (int j = i; j < length; j++)
data[j - 1] = data[j]; //注意此處J已經是元素所在的數據下標了
length--;
return x; //返回被刪除的值
}
//修改線性表中,第I個元素的值爲x
template <class DataType>
void CSeqList<DataType>::ModifyList(int i, DataType x)
{
if (length == 0) throw "下溢出";
if (i < 1 || i > length+1) throw "位置錯誤";
data[i - 1] = x;
}
//遍歷操作,按序號依次輸出各元素
template <class DataType>
void CSeqList<DataType>::PrintList()
{
for (int i = 0; i <length; i++)
cout<<data[i]; //依次輸出線性表的值
}