所以我试图删除链表中的所有元素,到目前为止我可以删除某些元素并删除列表尾部的元素。如何删除列表中的所有元素?我要指出,我们不允许在java中使用内置的链接列表方法
import java.util.*;
class Node{
//node class
char data;
Node next;
public Node(Character ch){
data = ch; next = null;
}
public Node next(){return next;}
public void setNext(Node p){
next = p;
}
public void set(Character ch){data = ch;}
public int data(){return data;}
}
class Reader{
Node head = null; Node tail = null;
public void add(Character ch){
Node nw = new Node(ch);
if(head == null){
head = nw; tail = nw;
}
else{
tail.setNext(nw);
tail = nw;
}
}
public void display(){
//display characters
Node k = head;
System.out.print('[');
while(k!=null){
if(k.next!=null)
System.out.print((char)k.data());
else
System.out.print((char)k.data());
k=k.next();
}
System.out.print(']');
}
public void del(){
Node k = head;
if (tail == null)
return;
else {
if (head == tail) {
head = null;
tail = null;
} else {
while (k.next != tail)
k = k.next;
tail = k;
tail.next = null;
}
}
}
public void delLine(){
//delete current line
}
}
class assignment9{
public static void main(String[]args){
Scanner in = new Scanner(System.in);
Reader r1 = new Reader();
System.out.println("Enter characters");
r1.add(in.next().charAt(0));r1.add(in.next().charAt(0));r1.add(in.next().charAt(0));r1.add(in.next().charAt(0));r1.add(in.next().charAt(0));
}
}
答案 0 :(得分:6)
只是做:
public void deleteAll(){
head = tail = null;
}
GC将负责其余的