Question

package data_structures_java ;

import java.util.LinkedList;

class Queue_implementation {
   private LinkedList<Float> list = new LinkedList<Float>();

   public void enqueue(Float item) {
      list.addLast(item);
   }   
   public Float dequeue() {    
      return list.poll();
   }
   public boolean hasItems() {
      return !list.isEmpty();
   }
   public int size() {
      return list.size();
   }
   public void addItems(Queue_implementation q) {
      while (q.hasItems())
         list.addLast(q.dequeue());
   }

}

I wanted to use arraylist to make my own queue. But then i would have to write function like add_only_to_front().

QUESTION: Is there any crucial difference what basic data structure you can use to make your own linked list, stack... Because I used array list to write my own stack implementation, and i wanted to use arraylist for queue, deque, linkedlist, map(possible?), heap(?).

This is my stack implementation using arraylist :

package data_structures_java;
import java.util.ArrayList ;
public class Stack_implementation {

    ArrayList<Integer> actual_stack ;
    int index_top ;

    public Stack_implementation( int size ){
          actual_stack = new ArrayList<Integer>(size) ;
          index_top = 0 ;

    }

    public int pop(){       
        System.out.println("popped 1 element!") ;
        int result = actual_stack.get(index_top) ;
        actual_stack.remove(index_top) ;
        --index_top ;

        return result ;
    }

    public void push(int element){
        if( index_top > actual_stack.size()){ 
            System.out.println("can't push on stack!");
            return ;
        }

    actual_stack.add(element) ;
    index_top++ ;

    }
    public void print_stack(){

        if(actual_stack.isEmpty() )System.out.println("stack is empty") ;


        for(int i = index_top-1 ; i >= 0 ; i--){
            System.out.println( "|\t" +  actual_stack.get(i)  + "\t|" ) ;
        }

    }


}
Was it helpful?

Solution

The difference is running time, therefore there isn't a 'correct' way. Although, some ways are much better than others.. Certain data structures implement Abstract Data Types (ADTs) better than others. For example, arrays are great for a stack because you can Push and Pop the elements easily; on the other hand, arrays are not very good for implementing a priority queue (depending on ordered/unordered you get linear running time). For most of the examples you list, an arrary (array list) works pretty well.

In my opinion, it's great to write your own ADTs. It helps you to better understand how the packages work and better implement their uses.

OTHER TIPS

1) If you are implementing a Queue your class should implement Queue interface

2) LinkedList is already a Queue

3) I think there is nothing wrong if you use ArrayList to implement a Queue, actually it is Adapter design pattern

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top