日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

静态数组实现线性表

發布時間:2025/6/15 编程问答 20 豆豆
生活随笔 收集整理的這篇文章主要介紹了 静态数组实现线性表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
List.h:

/*--List.h----------------------------------------------------------------------------
這個頭文件定義了用于處理線性表的List數據類型
基本操作包括
構造函數
empty:檢查線性表是否為空
insert:插入一個項
erase:刪除一個項
display:輸出列表

----------------------------------------------------------------------------------------*/

#include <iostream>

#ifndef LIST
#define LIST

const int CAPCITY=1024;
typedef int ElementType;

class List
{
public:
/************函數成員*************/*
??/*******構造函數***********/
??List();
??bool empty() const;
??void insert(ElementType item,int pos);
??void erase(int pos);
??void display() const;

private:
/*************數據成員***********/
??int mySize;//當前線性表的大小
??ElementType myArray[CAPCITY];//存儲線性表的數組
};


#endif


List.cpp #include "List.h"
#include <iostream>
using namespace std;

List::List()
{
??mySize=0;
}

bool List::empty() const
{
??return mySize==0;
}

void List::display() const
{
??for(int i=0;i<mySize;i++)
??{
????cout<<myArray[i]<<"\t";
??}
}

void List::insert(ElementType item, int pos)
{
??if(mySize == CAPCITY)
??{
????cout<<"空間不夠,無法插入元素!"<<endl;
????return ;
??}

??if(pos<0 || pos>mySize)
??{
????cout<<"插入位置錯誤!"<<endl;
????return;
??}

????

??for(int i=mySize;i>pos;i--)
??{
????myArray[i]=myArray[i-1];
??}
????myArray[pos]=item;
????mySize++;
????
}


void List::erase(int pos)
{
??if(mySize==0)
??{
????cout<<"線性表長度為0,無法刪除!"<<endl;
????return;
??}

??if(pos<0 || pos>=mySize)
??{
????cout<<"刪除位置錯誤!"<<endl;
????return;
??}

??for(int i=pos;i<mySize;i++)
??{
????myArray[i]=myArray[i+1];
??}
??mySize--;
}


檢測用的ListMain.cpp #include <iostream>
#include "List.h"
using namespace std;

int main()
{
??List intList;
??cout<<"構造線性表"<<endl;

??if(intList.empty())
??{
????cout<<"線性表:"<<"intList"<<"為空!"<<endl;
??}

??for(int i=0;i<9;i++)
??{
????cout<<"將"<<i<<"插入到位置"<<i/2<<"處"<<endl;
????intList.insert(i,i/2);
????intList.display();
????cout<<endl;
??}

??cout<<"intList是否為空?"<<(intList.empty()?"YES":"NO")<<endl;

??cout<<"在-1處插入元素!"<<endl;
??intList.insert(0,-1);

??cout<<"在10處插入元素!"<<endl;
??intList.insert(0,10);

??int index;
??cout<<endl;
??while(!intList.empty())
??{
????cout<<"請選擇要刪除元素的位置:"<<endl;
????cin>>index;
????intList.erase(index);
????intList.display();
????cout<<endl;
??}

??cout<<"intList 為空!"<<endl;
??cout<<"插入"<<CAPCITY<<"個整數"<<endl;

??for(int i=0;i<CAPCITY;i++)
????intList.insert(i,i);

??cout<<"再插入一個整數"<<endl;
??intList.insert(-1,0);
}

轉載于:https://blog.51cto.com/lp4083331/200018

總結

以上是生活随笔為你收集整理的静态数组实现线性表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。