1. 程式人生 > >數據結構-順序表

數據結構-順序表

collect 所在 alt img space 存儲 pre spa 數據結構和算法

大學以來一直沒怎麽認真學過數據結構,現在找工作了 都看重 學過數據結構和算法,所以現在開始認真學。

技術分享圖片

實現:接口(往後的鏈表文章都是使用這個接口)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _001_線性表
{
    interface IListDS<T>
    {
        int GetLength();
        void Clear();
        
bool IsEmpty(); void Add(T item); void Insert(T item, int index); T Delete(int index); T this[int index] { get; } T GetEle(int index); int Locate(T value); } }

順序表實現:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace _001_線性表 { /// <summary> /// 順序表 實現方式 /// </summary> class SeqList<T> : IListDS<T> { private T[] data;//存儲數據 private int count = 0;//存了多少數據 public SeqList(int size) //size最大容量 { data = new T[size]; count
= 0; } public SeqList() : this(10)//默認構造函數 容量是10 { } /// <summary> /// 返回指定序列號得元素 /// </summary> /// <param name="index"></param> /// <returns></returns> public T this[int index] => GetEle(index); /// <summary> /// 添加數據 /// </summary> /// <param name="item"></param> public void Add(T item) { if (count == data.Length)//當前數組已經存滿 { Console.WriteLine("當前順序表已經存滿,不允許再存入"); } else { data[count] = item; count++; } } /// <summary> /// 清空 /// </summary> public void Clear() { count = 0; } public T Delete(int index) { T temp = data[index]; for (int i = index+1; i < count; i++) // { data[i-1] = data[i];//把數據向前移動 } count--; return temp; } public T GetEle(int index) { if(count-1>=index && index>=0)//索引存在 { return data[index]; } else { Console.WriteLine("索引不存在"); return default(T); } } /// <summary> /// 取得數據個數 /// </summary> /// <returns></returns> public int GetLength() { return count; } /// <summary> /// 插入元素 /// </summary> /// <param name="item"></param> /// <param name="index"></param> public void Insert(T item, int index) { for (int i = count - 1; i >= index; i--) //反序遍歷 從後面開始移動元素 { data[i + 1] = data[i]; } data[index] = item; count++; } /// <summary> /// 是否為空 /// </summary> /// <returns></returns> public bool IsEmpty() { return count == 0; } /// <summary> /// 尋找該值所在得位置 /// </summary> /// <param name="value"></param> /// <returns></returns> public int Locate(T value) { for (int i = 0; i < count; i++) { if (data[i].Equals(value)) { return i; } } return -1; } } }

數據結構-順序表