0

こんにちは、ライブラリを使用せずに、個別にリンクされたリストを実装しています。リストの最後に要素を追加する際に問題が発生しています。誰でも私を助けてください。これが私のコードです:

public class SinglyLinkedList<T> implements GenericLinkedList<T> {
        private Node<T> head;
        private Node<T> tail;
        private int size;

        public SinglyLinkedList() {
            head = null;
            tail = null;
            size = 0;
                }
            public void addLast(T elem) {
            tail.next.element  = elem;
            size++;
        }

**public void addLast(T elem) {
            Node<T> newNode = new Node<T>();
            tail.next = null;
            newNode.element = elem;

        **
4

2 に答える 2

2

You specify the tail's next element, but you should also consider that the inserted element becomes the new tail itself. In short:

  1. Create a new node.
  2. Store the element on it.
  3. Make the tail point to that node. (the current tail becomes, then, the nth - 1 element).
  4. Make the newly inserted element your new tail.
  5. Increment the list's size.

Your current problem is also related to steps 1 and 3. You don't define a Node object to store and tail.next should be null if it is truly the tail of the list.

于 2013-11-13T17:54:53.113 に答える
1

ここにsinglylinkedlistの完全なコードがあります。
SinglyLinkedList

public class SinglyLinkedList<T> {
    private Node<T> head;
    private Node<T> tail;
    private Node<T> temp;
    private int size;

    public SinglyLinkedList() {
        head = null;
        tail = null;
        size = 0;
    }

    public void addLast(T elem) {
        if(head == null){
            head = new Node<T>();
            head.element = elem;
            tail = head;
            size++;
        } else  {
            temp = new Node<T>();
            temp.element = elem;
            tail.next = temp;
            temp.prev = tail;
            tail = temp;
            size++;
        }  

    }
    void print(){
        temp = head;
        while(temp  != null){
            System.out.println(temp.element);
            temp = temp.next;
        }
    }
    public static void main(String[] args) {
        SinglyLinkedList<Integer> list = new SinglyLinkedList<>();
        list.addLast(1);
        list.addLast(2);
        list.addLast(3);
        list.addLast(4);
        list.addLast(5);
        list.addLast(6);
        list.print();

    }
}

ノード

public class Node<T>{
    Node<T> prev;
    Node<T> next;
    T element;
    public Node() {
    }
}
于 2013-11-13T18:37:25.030 に答える