gpt4 book ai didi

java - 删除链表中的所有元素

转载 作者:行者123 更新时间:2023-12-01 08:12:35 25 4
gpt4 key购买 nike

所以我试图删除链接列表中的所有元素,到目前为止我可以删除某些元素并删除列表尾部的元素。我将如何删除列表中的所有元素?我要指出的是,我们已经不允许在 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));

}
}

最佳答案

就这样做:

public void deleteAll(){  
head = tail = null;
}

GC 会处理剩下的事情

关于java - 删除链表中的所有元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16135545/

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