【问题标题】:Writing a removeLast method编写 removeLast 方法
【发布时间】: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(以及数据结构),我编写了这个程序/类以更好地理解堆栈/数据管理 就像我说的,我会在库中使用预先编写的代码,但是我发现它很复杂且经过优化,我正在尝试复习基础知识。

标签: c# arrays


【解决方案1】:

你只需要写

public int removeLast() 
{
    if (isEmpty())
        throw new Exception("List is Empty");

    count--;
    return values[count];
}

这将返回 values 数组中的最后一项,而不改变其大小,但减少跟踪实际插入数组中的项的变量。
请注意,我不会尝试更改 count 变量指向的位置的值。它仍然存在,直到您覆盖它添加另一个值

所以你仍然可以写这个

// Creates an array with space for 10 ints 
LinearArrayList la = new LinearArrayList();
la.addLast(34);   
la.addLast(23);   
la.addLast(56);   
la.addLast(467);
la.addLast(43);
la.addLast(666);
la.addLast(7989);
la.addLast(82);
la.addLast(569);
la.addLast(100);  
int value = la.removeLast();

// This will work because you still have a slot free in the 10 ints array 
la.addLast(1110);

// While this will fail because the array has now all slots filled
la.addLast(9435);

【讨论】:

    【解决方案2】:

    Sybren 答案的替代方案:

    int lastValue = values[values.Length - 1];
    int[] newValues = new int[values.Length - 1];
    Array.Copy(values, newValues, newValues.Length);
    values = newValues;
    return lastValue;
    

    int lastValue = values[values.Length - 1];
    Array.Resize(values, values.Length - 1);
    return lastValue;
    

    如果您不想使用Array 类的任何现有方法,您还可以:

    int lastValue = values[values.Length - 1];
    int[] newValues = new int[values.Length - 1];
    for (int i = 0; i < newValues.Length; i++)
    {
        newValues[i] = values[i];
    }
    values = newValues;
    return lastValue;
    

    编辑

    算了,照@Steve 说的去做吧。

    【讨论】:

    • 谢谢,最后一个答案有点像我想要的,我真的不想使用现有的 Array 方法。
    • 这使得不同的数组具有更小的尺寸。这意味着初始构造函数大小不再有效,因此它不能在前一个最后位置存储新值。要完整,您需要一个 add 方法,如果大于当前长度,则调整数组的大小。换句话说,你需要重新实现一个 List
    【解决方案3】:

    这是一种方法。您正在将数组转换为列表,从列表中获取最后一个元素,从列表中删除最后一个元素,然后将其转换回数组。

        var numbersList = values.ToList();
        var last = numbersList.Last();
        numbersList.Remove(last);
        values = numbersList.ToArray();
        return last;
    

    【讨论】:

      猜你喜欢
      • 2016-06-10
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 1970-01-01
      • 2016-10-13
      • 1970-01-01
      • 2014-02-23
      • 2021-05-20
      相关资源
      最近更新 更多