单链表(c++)

线性表的增删改查--c++
  1 #include "stdafx.h"
  2 #include <iostream>
  3 using namespace std;
  4 const int MaxSize = 100;
  5 
  6 class SeqList{                      //定义一个SeqList类
  7 private:
  8  int data[MaxSize];              //存放数据元素的数组
  9  int length;                     //线性表的长度
 10 public:
 11  SeqList(){length = 0;}          //无参构造函数,建立一个空的顺序表
 12  SeqList(int a[],int n);         //创建一个长度为n的顺序表;
 13  ~SeqList(){}                    //析构函数为空
 14  int Length(){return length;}    //求线性表的长度
 15  int Get(int i);                 //按位查找,在线性表中查找第i个元素
 16  int locate(int x);              //按值查找,在线性表中查找值为x的元素序号
 17  void Insert(int i,int x);       //插入操作,在线性表中第i个位置插入值为x的元素
 18  int Delete(int i);              //删除操作,删除线性表的第i个元素
 19  void printList();               //遍历操作,按序号依次输出各元素
 20 };
 21 
 22 SeqList::SeqList(int a[],int n){
 23  if(n>MaxSize) throw "参数非法";
 24  for(int i = 0;i<n;i++)
 25   data[i] = a[i];
 26  length = n;
 27 }
 28 
 29 int SeqList::Get(int i){
 30  if(i < 1 && i > length) throw "查找的范围非法";
 31  else
 32   return data[i-1];
 33 }
 34 
 35 int SeqList::locate(int x){
 36  for(int i = 0;i < length;i++)
 37   if(x == data[i])
 38    return i+1;
 39   return 0;
 40 }
 41 
 42 void SeqList::Insert(int i,int x){
 43  if(length>=MaxSize) throw "上溢";
 44  if(i<1||i>length+1) throw "位置";
 45  for(int j = length;j>=i;j--)
 46   data[j] = data[j-1];
 47  data[i-1] = x;
 48  length++;
 49  for(int j = 0;j<length;j++){
 50   cout<<data[j]<<" ";
 51  }
 52 }
 53 
 54 int SeqList::Delete(int i){
 55  if(length>=MaxSize) throw "下溢";
 56  if(i<1||i>length) throw "位置";
 57  int x =data[i-1];
 58  for(int j = i;j<=length;j++)
 59   data[j-1] = data[j];
 60  length--;
 61  return x;
 62 }
 63 
 64 void SeqList::printList(){
 65  for (int i = 0; i < length; i++){
 66   cout << data[i] <<" ";
 67  }
 68  cout << endl;
 69 }
 70 
 71 int _tmain(int argc, _TCHAR* argv[])
 72 {
 73  int n;
 74  cin>>n;
 75  int * a = new int[n];                 //动态创建数组a;
 76  for(int i = 0;i < n;i++){             //输入元素
 77   cin >> a[i];
 78  }
 79  SeqList example(a,n);                 //定义一个SeqList 的对象,并初始化
 80  cout<<"数组的长度  ";
 81  cout<<example.Length()<<endl;    
 82  cout<<"输入要查找的元素位置   ";
 83  int i;
 84  cin>>i;
 85  cout<<example.Get(i)<<endl;
 86  cout<<"在第j个元素插入数字x输入j,x   ";
 87  int j,x;
 88  cin>>j>>x;
 89  example.Insert(j,x);
 90  cout<<endl;
 91  cout<<"查找数值为y的元素下标输入y   ";
 92  int y;
 93  cin>>y;
 94  cout<<example.locate(y)<<endl;
 95  cout<<"删除第m个元素输入m   ";
 96  int m;
 97  cin>>m;
 98  cout<<example.Delete(m)<<endl;
 99  cout<<"打印SeqList对象      ";
100  example.printList();
101  delete a;
102  return 0;
103 }
View Code

 

posted @ 2016-11-20 16:47  初相见  阅读(501)  评论(0)    收藏  举报