public class LinkedSList<E> implements List<E>{ private SLNodel head; private int size; public LinkedSList() { head = new SLNodel(); size=0; } @Override public int size() { return size; } @Override public boolean isEmpty() { return size==0; } @Override public boolean contains(Object o) { SLNodel p = head; while (p.getNext()!=null){ if(p.getData().equals(o)){ return true; } p = p.getNext(); } return false; } @Override public boolean add(E e) { if(size==0){ head.setDate(e); head.setNext(new SLNodel()); size++; return true; }else{ SLNodel p = head; while (p.getNext()!=null){ SLNodel target = p.getNext(); if(target.getData()==null){ target.setDate(e); target.setNext(new SLNodel()); size++; return true; }else{ p = p.getNext(); } } } return false; } @Override public boolean remove(Object o) { int index = indexOf(o); if(index!=-1){ remove(index); return true; } return false; } @Override public E get(int index) { if(index<0||index>size-1){ return null; } SLNodel p = head; int i =0; while (p.getNext()!=null){ if(index==i){ return (E)p.getData(); }else{ p = p.getNext(); i++; } } return null; } @Override public E set(int index, E element) { if(index<0||index>size-1){ return null; } SLNodel p = head; int i =0; while (p.getNext()!=null){ if(index==i){ p.setDate(element); return element; }else{ p = p.getNext(); i++; } } return null; } @Override public void add(int index, E element) { if (index < 0 || index > size - 1) { throw new RuntimeException("索引越界"); }else if(index==0){ SLNodel p = new SLNodel(element,head); head=p; size++; }else{ SLNodel p = head; int i = 0; while (p.getNext() != null) { if (index-1 == i) { //前驱节点 SLNodel q =new SLNodel(element,p.getNext()); p.setNext(q); size++; return; } else { p = p.getNext(); i++; } } } } @Override public E remove(int index) { if (index < 0 || index > size - 1) { throw new RuntimeException("索引越界"); }else if(index==0){ E e = (E)head.getData(); head.setDate(null); size--; return e; }else{ SLNodel p = head; int i = 0; while (p.getNext() != null) { if (index-1 == i) { //前驱节点 E e = (E)p.getNext().getData(); p.setNext(p.getNext().getNext()); size--; return e; } else { p = p.getNext(); i++; } } } return null; } @Override public int indexOf(Object o) { SLNodel p = head; int index = 0; while (p.getNext()!=null){ if(p.getData().equals(o)){ return index; } p = p.getNext(); index++; } return -1; } @Override public int lastIndexOf(Object o) { SLNodel p = head; int index = size-1; while (p.getNext()!=null){ if(p.getData().equals(o)){ return index; } p = p.getNext(); index--; } return -1; } }
版权声明:
本文来源网络,所有图片文章版权属于原作者,如有侵权,联系删除。
本文网址:https://www.bianchenghao6.com/java-jiao-cheng/17291.html