單鏈表(c++)

來源:互聯網
上載者:User

標籤:throw   private   delete   順序表   線性表   尋找   data   列印   row   

#include "stdafx.h"
#include <iostream>
using namespace std;
const int MaxSize = 100;

class SeqList{                      //定義一個SeqList類
private:
 int data[MaxSize];              //存放資料元素的數組
 int length;                     //線性表的長度
public:
 SeqList(){length = 0;}          //無參建構函式,建立一個空的順序表
 SeqList(int a[],int n);         //建立一個長度為n的順序表;
 ~SeqList(){}                    //解構函式為空白
 int Length(){return length;}    //求線性表的長度
 int Get(int i);                 //按位尋找,線上性表中尋找第i個元素
 int locate(int x);              //按值尋找,線上性表中尋找值為x的元素序號
 void Insert(int i,int x);       //插入操作,線上性表中第i個位置插入值為x的元素
 int Delete(int i);              //刪除操作,刪除線性表的第i個元素
 void printList();               //遍曆操作,按序號依次輸出各元素
};

SeqList::SeqList(int a[],int n){
 if(n>MaxSize) throw "參數非法";
 for(int i = 0;i<n;i++)
  data[i] = a[i];
 length = n;
}

int SeqList::Get(int i){
 if(i < 1 && i > length) throw "尋找的範圍非法";
 else
  return data[i-1];
}

int SeqList::locate(int x){
 for(int i = 0;i < length;i++)
  if(x == data[i])
   return i+1;
  return 0;
}

void SeqList::Insert(int i,int x){
 if(length>=MaxSize) throw "上溢";
 if(i<1||i>length+1) throw "位置";
 for(int j = length;j>=i;j--)
  data[j] = data[j-1];
 data[i-1] = x;
 length++;
 for(int j = 0;j<length;j++){
  cout<<data[j]<<" ";
 }
}

int SeqList::Delete(int i){
 if(length>=MaxSize) throw "下溢";
 if(i<1||i>length) throw "位置";
 int x =data[i-1];
 for(int j = i;j<=length;j++)
  data[j-1] = data[j];
 length--;
 return x;
}

void SeqList::printList(){
 for (int i = 0; i < length; i++){
  cout << data[i] <<" ";
 }
 cout << endl;
}

int _tmain(int argc, _TCHAR* argv[])
{
 int n;
 cin>>n;
 int * a = new int[n];                 //動態建立數組a;
 for(int i = 0;i < n;i++){             //輸入元素
  cin >> a[i];
 }
 SeqList example(a,n);                 //定義一個SeqList 的對象,並初始化
 cout<<"數組的長度  ";
 cout<<example.Length()<<endl;   
 cout<<"輸入要尋找的元素位置   ";
 int i;
 cin>>i;
 cout<<example.Get(i)<<endl;
 cout<<"在第j個元素插入數字x輸入j,x   ";
 int j,x;
 cin>>j>>x;
 example.Insert(j,x);
 cout<<endl;
 cout<<"尋找數值為y的元素下標輸入y   ";
 int y;
 cin>>y;
 cout<<example.locate(y)<<endl;
 cout<<"刪除第m個元素輸入m   ";
 int m;
 cin>>m;
 cout<<example.Delete(m)<<endl;
 cout<<"列印SeqList對象      ";
 example.printList();
 delete a;
 return 0;
}

單鏈表(c++)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.