从列表中删除第一项?
问题描述:
我正在研究编程语言中指针的概念,并且我遇到了用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
+1
你的意思是? if(start == null){sout“list is empty”} else {start = start.nextn; } – user3816423 2014-08-29 16:15:19
+0
非常。我想你有这个。 – jh314 2014-08-29 17:55:46
这就是助教是。安排与他们的约会...你会得到更多的建立与他们的关系,而不仅仅是在这里得到这个答案。 ;) – 2014-08-29 15:53:44
@samyi假设OP在一所学校参加课程,而且学校有TA,这两个都不是从问题中提出的。 – jpw 2014-08-29 15:55:36
SO是寻找简单出路的学生的温床。声誉= 1的userxxxxxx ....几乎可以保证做作业。虽然关于学校可能没有助教的有效点。我试图教他/她如何钓鱼......而不是给予鱼。 ;) – 2014-08-29 16:18:17