我实现了一个链接列表,每次调用函数时,它都会将其元素放在列表前面,例如:
30-->40
|
first
//add 50
30-->40-->50
|
first
我实现的代码如下:
public class Node {
public int elem;
Node next;
public Node(int e){
this.elem=e;
}
}
public class List {
Nodo list;
Nodo first;
public void addFront(int n){
Nodo temp=new Nodo(n);
if (list==null){
first=temp;
}
else{
list.next=temp;
}
list=temp;
}
public void print(){
Nodo current;
current=first;
while (current!=null){
System.out.println(current.elem);
current=current.next;
}
}
public Nodo deletefirst(){
first=first.next;
return list;
}
public int size(){
Nodo temp;
temp=first;
int c=0;
while (temp!=null){
c++;
temp=temp.next;
}
return c;
}
当我做这样的事情时,我遇到的问题是在我的主程序中:
List list4=new List();
list4.addFront(10);
list4.addFront(20);
list4.addFront(40);
list4.addFront(60);
list4.addFront(80);
for (int i=0;i<list4.size();i++){
List4.deletefirst();
System.out.println("List");
List4.print();
}
可视化列表如下:
list
20
40
60
80
list
40
60
80
list
60
80
如何更改我的代码,以便它打印列表中缺失的值,我的意思是:
list
80
list
null
有什么帮助吗?
最佳答案
添加到列表前面:
public class List {
Nodo first;
public void addFront(int n){
Nodo temp = new Nodo(n);
temp.next = first;
first = temp:
}
通常first
被命名为head
,如“列表的头部”。
只需一个字段即可指向第一个节点。
调试代码最好通过心理执行在纸上完成。
关于java - 删除链表的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56463365/