P
P
parkito2016-08-07 19:14:38
Java
parkito, 2016-08-07 19:14:38

How to create a queue based on a singly linked list in java?

Hello. Please tell me how to organize a queue on a single-linked list.
Stack is easy.

public class List<T> {
    public int key;
    public T data;
    public List next;

    List(int key, T data) {
        this.key = key;
        this.data = data;
    }

    T getData() {
        return this.data;
    }
    void show(){
        System.out.println(key+") "+data+" ");
    }
}

public class LinkedList<T> {
    private int size;
    private List first;

    public LinkedList() {
        first = new List(0, 0);
        size = 0;
    }

    public void add(T element) {
        List newList = new List(size, element);
        size++;
        newList.next = first;
        first = newList;

    }

    public void display() {
        List<Integer> current = first;
        while (current != null) {
            System.out.println(current.getData());
            current = current.next;
        }
    }
}

I can organize such a thing in c++ using pointers. But this is where the problem bogged me down.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
M
MikkiMouse, 2016-08-07
@MikkiMouse

In addition to linking to the first element, you can add a link to the last. Elements are added through a link to the last one, and retrieved through a link to the first one.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question