【发布时间】:2020-08-17 12:09:10
【问题描述】:
我正在尝试从数组中删除一个数字。我试过按照教程进行操作,该方法会删除我输入的数字,如果有重复,它会删除第一个重复的数字,但是它总是在开始时显示 0,即使 0 不是数组中的数字。例如。假设我有一个数字列表 1, 12, 44, 55, 66, 17, 8, 4, 12, 70,我删除数字 44,输出为:0, 1, 12, 55, 66, 17, 8, 4、12、70。我不知道为什么会出现 0 以及如何摆脱它。任何帮助将不胜感激。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace deletenumber
{
class Program
{
public class Node
{
public int data;
public Node next;
};
static Node add(Node head, int data)
{
Node temp = new Node();
Node current;
temp.data = data;
temp.next = null;
if (head == null)
head = temp;
else
{
current = head;
while (current.next != null)
current = current.next;
current.next = temp;
}
return head;
}
static void print(Node head)
{
while (head != null)
{
Console.Write(head.data + " ");
head = head.next;
}
}
static Node List(int[] a, int n)
{
Node head = null;
for (int i = 1; i <= n; i++)
head = add(head, a[i]);
return head;
}
public static void Main(String[] args)
{
int n = 10;
Random r = new Random();
int[] a;
a = new int[n + 1];
a[0] = 0;
int i;
for (i = 1; i <= n; i++)
a[i] = r.Next(1, 100);
Node head = List(a, n);
Console.WriteLine("List = ");
print(head);
Console.ReadLine();
Console.WriteLine();
Console.WriteLine("What number do you want to delete?");
int item = Convert.ToInt32(Console.ReadLine());
Console.WriteLine();
int index = Array.IndexOf(a, item);
a = a.Where((e, k) => k != index).ToArray();
Console.WriteLine(String.Join(", ", a));
Console.ReadLine();
}
}
}
【问题讨论】:
-
a[0] = 0;在静态主目录中?
-
如果我不迷茫,你把a[0] = 0,并没有覆盖它
-
a[0] = 0;- 你的数组总是有那个零......但是在你的 List 函数中,你从索引 1 开始,所以你第一次看不到“0”(当你调用print(head),但您确实稍后将数组转储到控制台时会看到它 -
但是我如何改变它,使它不显示 0
标签: c# arrays linked-list