gpt4 book ai didi

java - 从列表中删除第一项?

转载 作者:太空宇宙 更新时间:2023-11-04 06:34:43 25 4
gpt4 key购买 nike

我正在研究编程语言中指针的概念,并且遇到了用 Java 编写的这个算法,我应该删除此列表的第一项。我是初学者,我发现自己很难解决这个问题。

public class mylist {

private static class mylist
{
public int num;
public mylist nextn;
}

public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
mylist start = null;
mylist end = null;
mylist aux;
mylist before;
int op, number, found;
do{
System.out.println("1- insert number in the beginning list");
System.out.println("2- insert in the end of the list");
System.out.println("3- query list");
System.out.println("4- remove from list"); System.out.println("5- empty list");
System.out.println("6- exit");
System.out.print("choose: ");
op = input.nextInt();
if(op < 1||op>6)
{
System.out.println("invalid number");
}
if(op == 1)
{
System.out.println("type the number to be inserted in the beginning of the list");
mylist newl = new mylist();
newl.num = input.nextInt();
if(start == null)
{
start = newl;
end = newl;
newl.nextn = null;
}
else
{
newl.nextn = start;
start = newl;
}
System.out.println("number inserted");
}
if(op == 2)
{
System.out.println("type the number to be inserted in the end of the list");
mylist newl = new mylist();
newl.num = input.nextInt();
if(start == null)
{
start = newl;
end = newl;
newl.nextn = null;
}
else
{
end.nextn = newl;
end = newl;
newl.nextn = null;
}
System.out.println("number inserted");
}
if(op == 3)
{
if(start == null)
{
System.out.println("list is empty");
}
else
{ System.out.println("\nquerying the list\n");
aux = start;
while(aux!=null)
{
System.out.print(aux.num+ " ");
aux = aux.nextn;

}
}
}
if(op == 4)
{
if(start == null)
{
System.out.println("list is empty");
}
else
{
System.out.println("\ntype the number to be removed:\n");
number = input.nextInt();
aux = start;
before = null;
found = 0;

while(aux!=null)
{
if(aux.num == number)
{
found = found +1;
if(aux == start)
{
start = aux.nextn;
aux = start;
}
else if(aux == end)
{
before.nextn = null;
end = before;
aux = null;
}
else
{
before.nextn =aux.nextn;
aux = aux.nextn;
}
}
else
{
before = aux;
aux =aux.nextn;
}
}
if(found ==0) {
System.out.append("number not found");
}
else if(found ==1)
{
System.out.append("number removed once!");
}
else
{
System.out.append("number removed "+found+" times!");
}
}
}
if(op == 5)
{
if(start == null)
{
System.out.println("empty list");
}
else
{
start = null;
System.out.println("emptied list");
}
}
}while(op !=6);
}

}

最佳答案

只需将 start 设置为列表的第二个元素:

start = start.nextn

关于java - 从列表中删除第一项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25571841/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com