Mam za zadanie zaimplementować listę jednokierunkową i mam problem taki,że po wywołaniu metody addFirst i addAtPosition nie dodaje mi na początku listy tylko na jej końcu.
Oto mój kod:
public class ListOne<T> implements IList<T> {
private ElemOne poczatek;
private ElemOne koniec;
private ElemOne next;
private T zawiera;
int size;
public ListOne()
{
poczatek=null;
koniec=null;
size=0;
}
public boolean czyPusta()
{
return (poczatek == null);
}
public void addFirst(T newData)
{
ElemOne wezel=new ElemOne(newData,poczatek);
if(czyPusta())
{
koniec=wezel;
poczatek=wezel;
}
else {
ElemOne temp = poczatek;
while(temp.getNext() != null) {
temp = temp.getNext();
}
ElemOne newNode = new ElemOne(newData,null);
temp.setNext(newNode);
}
}
public void addLast(T newData)
{
ElemOne newWezel = new ElemOne(newData,null);
if(czyPusta())
{
poczatek = newWezel;
koniec=newWezel;
}
else{
koniec.next=newWezel;
koniec=newWezel;
}
}
public void addAtPosition(T newData, int position) throws ListException
{
if ((position < 0) || (position > size))
throw new ListException("zly index");
if (position == 0) {
addFirst(newData);
}
size++;
}
public int size()
{
return size;
}
// public T removeFirst() throws ListException
{
/* if (czyPusta())
{
throw new ListException("lista jest pusta!!!!");
}
else
{
ElemOne pomoczniczy = poczatek;
poczatek = poczatek.getNext();
return pomoczniczy;
}*/
}
// public T removeLast() throws ListException
{
}
// public T remove(int position) throws ListException
{
}
// public int find(T dataToFind)
{
}
/* public boolean contains(T data)
{
for(int i = 1;i<=size();i++) {
if(getData(i).equals(data)) {
return true;
}
}
return false;
} */
public void print()
{
int count = 0;
if(poczatek == null) {
System.out.println("\n List is empty !!");
} else {
ElemOne temp = poczatek;
while(temp.getNext() != null) {
System.out.println("count("+count+") , node value="+temp.getData());
count++;
temp = temp.getNext();
}
}
}
public static void main(String[] args) {
ListOne aa=new ListOne();
System.out.println(aa.czyPusta());
try{
aa.addLast("sad");
aa.addFirst("baz");
aa.addFirst("foo");
aa.print();
aa.addAtPosition("aaaaaaa",0);
aa.print();
}catch(ListException e){e.printStackTrace();}
System.out.println(aa.czyPusta());
//aa.print(aa.getNext());
}
}
i klasa ElemOne:
public class ElemOne<T> {
private T data;
ElemOne next;
public ElemOne(T data) {
this.data = data;
}
public ElemOne(T data, ElemOne next) {
this.data = data;
this.next = next;
}
public ElemOne() {
this.data = data;
this.next = next;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public ElemOne getNext() {
return next;
}
public void setNext(ElemOne next) {
this.next = next;
}
}
Z góry dzięki za pomoc