簡體   English   中英

從鏈接列表中刪除所有元素

[英]Deleting all elements from a Linked List

因此,我試圖刪除鏈接列表中的所有元素,到目前為止,我可以刪除某些元素並刪除列表末尾的元素。 我將如何刪除列表中的所有元素? 我要指出的是,我們已經不允許將內置方法用於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將負責其余的工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM