【发布时间】:2014-11-03 01:37:54
【问题描述】:
情况:
我是 C# 新手,目前正在学习基础知识,同时也在完善我的数据结构,我决定创建一个对线性数组执行多个函数的类,因为有人建议我应该开始使用线性阵列,然后在圆形阵列上工作。
我的班级目前提供的方法有:
- 在数组的最前面位置添加一个项目,
- 将项目添加到数组的最后位置,
- 删除数组中的第一项,
- 删除数组中的最后一项,//todo
- 清除当前数组列表中的值,
- 向用户显示数组列表内容。
问题:
我在构建删除数组最后一项的方法时遇到困难,我在网上查看过,预先编写的方法似乎很复杂,由于我的经验不足,我无法理解它们。我意识到其他人编写这样的方法一定很容易,但我真的很难过。
我想学习如何以最简单易懂的方式编写一个删除数组中最后一个值的方法。这是我的 LinearArrayList 类的当前代码。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace arraydatastructuresactual
{
public class LinearArrayList
{
private int count; //how many numbers currently stored
private int[] values; //array to hold values entered into list
//constructors
/// <summary>
/// //creates a linear array that can hold max values
/// </summary>
/// <param name="max"></param>
public LinearArrayList(int max)
{
count = 0;
values = new int[max]; //makes the linear array as big as the max value
}
/// <summary>
/// //default constructor sets capacity to 10
/// </summary>
public LinearArrayList()
{
count = 0;
values = new int[10];
}
/// <summary>
/// returns true if list is empty
/// otherwise turns false
/// </summary>
/// <returns>true if empty otherwise false</returns>
public bool isEmpty()
{
return (count == 0);
}
/// <summary>
/// returns true if list is full
/// otherwise turns false
/// </summary>
/// <returns>true if full otherwise false</returns>
public bool isFull()
{
return (values.Length <= count);
}
/// <summary>
/// if not full adds value to the end of list
/// throws exception if list is fulll
/// </summary>
/// <param name="value">value to add to end of list</param>
public void addLast(int value) //adds an item to the last position in the array.
{
if (isFull())
{
throw new Exception("List Full");
}
else
{
values[count++] = value;
}
}
public void addFirst(int value) //Adds an item to the first position in the array.
{
if (isFull())
{
throw new Exception("List Full");
}
else
{
for (int i = count; i > 0; i--)
{
values[i] = values[i--];
}
values[0] = value;
count++;
}
}
public int removeFirst() //removes the first item from the array
{
if (isEmpty())
throw new Exception("List is Empty");
int value = values[0];
count--;
for (int i = 0; i < count; i++)
{
values[i] = values[i + 1];
}
return value;
}
public int removeLast() //todo //removes the last item from the array
{
if (isEmpty())
throw new Exception("List is Empty");
int value = values[0];
count--;
for (int i = count; i < count; i++)
{
values[i] = values[i + 1];
}
return value;
}
public void displayUI()//displays contents of list
{
}
public void destroy() //Empties The List
{
}
}
}
如果有人可以分享他们关于我将如何实现这一目标的经验,那么非常感谢,我尝试重新使用我的 removeFirst 方法,但我搞砸了,尝试了几次,我现在完全被难住了。
【问题讨论】:
-
Last = value[count] 然后递减计数?
-
你知道已经有一个 Array 类...对吗? msdn.microsoft.com/en-us/library/…
-
我主要学习 c# 和 IDE(以及数据结构),我编写了这个程序/类以更好地理解堆栈/数据管理 就像我说的,我会在库中使用预先编写的代码,但是我发现它很复杂且经过优化,我正在尝试复习基础知识。