My Array List Class에서 add (int i, T t) 메서드를 사용하여 index에 의해 지정된 위치보다 전에 Array List에 새 요소를 삽입하려고합니다. 또한 My Array List Class에서 Clear() 메서드를 사용하여 Array List에서 모든 요소를 제거하려고합니다.ArrayList에 요소를 추가하고 ArrayList에서 요소를 제거하는 구현
어떻게 구현할 수 있습니까?
내 배열 목록 클래스 :
공용 클래스 MyArrayList {
private int n=0; //initial size of the array list
private MyArrayListElement<T> firstElement;//the first element of the array list
//Gets the element at index i
private MyArrayListElement<T> getElement(int i){
if(firstElement == null) return null;
int c = 0;
MyArrayListElement<T> x=firstElement;
while(x!=null){
if(c==i) return x;
x=x.getNext();
c++;
}
return null;
}
//Gets the element value at index i
public T get(int i){
MyArrayListElement<T> element = getElement(i);
if(element!=null) return element.getValue();
return null;
}
//Removes the element at index i
public void remove(int i){
MyArrayListElement<T> x= getElement(i);
if(x==null) return;
if(x.getPrevious()!=null){
x.getPrevious().setNext(x.getNext());
}
if(x.getNext()!=null){
x.getNext().setPrevious(x.getPrevious());
}
if(x==firstElement){
firstElement = x.getNext();
}
n--; // decrement the size of the array list
}
//Adds a new element to the end
public void add(T t){
MyArrayListElement<T> element = new MyArrayListElement<T>(t);
if(firstElement == null){
firstElement = element;
}else{
MyArrayListElement<T> lastElement=getElement(n-1); //Get the last element
lastElement.setNext(element); //Add new element to the end
element.setPrevious(lastElement);//Update previous element
}
n++; //increment the size
}
//Returns the number of elements in the array list
public int size(){
return n;
}
public String toString(){
String str ="{";
for(int i=0;i<n;i++){
str+=get(i);
if(i<n-1){
str+=",";
}
}
str+="}";
return str;
}
public void add(int index, T t) {
}
public void clear(){
}
내 배열 목록 요소 클래스 :
공용 클래스 MyArrayListElement {
private T value; // This is the data stored in this element
private MyArrayListElement <T> next; // the next element
private MyArrayListElement <T> previous; // the previous element
//Constructor gets an object of type <T> as an argument
public MyArrayListElement(T t) {
value = t; //stores the object in the instance variable "value"
}
public void setValue(T val){
value = val; //change the stored object
}
public void setNext(MyArrayListElement <T> n){
next = n; //set the link to the next element
}
public MyArrayListElement<T> getNext() {
return next; //get the next element
}
public T getValue(){
return value; //get the data stored in this element
}
public MyArrayListElement <T> getPrevious() {
return previous; //get the previous element
}
public void setPrevious(MyArrayListElement <T> previous) {
this.previous = previous; //set the link to the previous element
}
}
이 숙제가 있습니까? 아니면 왜 당신 자신의 ArrayList를 구현하고 싶습니까? – keuleJ
정말로 숙제를하고 싶지 않다면, 검색 엔진을 사용하고 이중 연결된 목록을 검색하면 알고리즘을 찾을 수 있습니다 (의사 코드에 위키피디아에 하나 있습니다). – StephaneM
그 이름에서 알 수 있듯이 배열로 지원되는 배열 목록이 아닙니다. 그것은 연결된 목록입니다. –