簡體   English   中英

此教科書中單鏈表的實現有什么問題?

[英]Whats wrong with this textbook implementation of Singly Linked List?

在教科書“使用Java 6E進行數據結構和算法”中可以找到該實現,這在嘗試創建新Node時在addFirst和addLast方法中給我一個錯誤。 它說不能從SinglyLinkedList.Node轉換為SinglyLinkedList.Node

這是代碼

public class SinglyLinkedList<E> {


private static class Node<E>{
    private E element;
    private Node<E> next;
    public Node(E e, Node<E> n){
        element = e;
        next = n;
    }
    public E getElement(){
        return element;
    }
    public Node<E> getNext(){
        return next;
    }
    public void setNext(Node<E> n){
        next = n;
    }
}

private Node<E> head = null;           //head node of list or null if empty
private Node<E> tail = null;            // tail node of list or null if empty
private int size = 0;           //size of list

public SinglyLinkedList(){}     //constructs an initially empty list

public int size(){              //size getter
    return size;
}

//accessors
public boolean isEmpty(){       //isList empty getter
    return size ==0;
}

public E first(){               //head data getter
    if(isEmpty()){
        return null;
    }
    return head.getElement();
}

public E last(){                //tail data getter
    if(isEmpty()){
        return null;
    }
    return tail.getElement();
}

//updators
public void addFirst(E e){
    head = new Node<>(e, head);
    if(size == 0){
        tail = head;
    }
    size++;
}

public void addLast(E e){
    Node<E> newest = new Node<>(e, null);
    if(isEmpty()){
        head = newest;
    }
    else{
        tail.setNext(newest);
    }
    tail = newest;
    size++;
}

public E removeFirst(){
    if(isEmpty()) return null;

    E answer = head.getElement();
    head = head.getNext();
    size--;
    if(size==0)
        tail = null;
    return answer;
}
}

更新您的addFirstaddLast方法,如下所示:

public void addFirst(E e) {
    head = new Node<E>(e, head); // update here
    if(size == 0){
        tail = head;
    }
    size++;
}

public void addLast(E e){
    Node<E> newest = new Node<E>(e, null); // update here
    if(isEmpty()){
        head = newest;
    }
    else{
        tail.setNext(newest);
    }
    tail = newest;
    size++;
}

然后,我可以創建和使用它。

public class A {
    public static void main(String[] args) {
        SinglyLinkedList list = new SinglyLinkedList<Integer>();
        list.addFirst(new Integer(1));
        list.addLast(new Integer(2));
        System.out.println(list.first());
        System.out.println(list.last());
    }
}

暫無
暫無

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

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