0

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

    }
}
4

1 回答 1

6

做就是了:

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

GC 会处理剩下的事情

于 2013-04-21T20:00:33.923 回答