链表简单实现
```java
class Node<T>{
T name;
public Node(T name, Node next, Node previdous) {
this.name = name;
this.next = next;
this.previdous = previdous;
}
Node<T> next;
Node<T> previdous;
@Override
public String toString() {
return "Node{" +
"name='" + name + '\'' +
'}';
}
}
*节点的实现
public class MyLinkedList<T> implements Iterable<T>{
private int theSize;
private int modCount;
private Node<T> beginMarker;
private Node<T> endMarker;
public MyLinkedList(){
clear();
}
public void clear(){
beginMarker=new Node<T>(null,null,null);
endMarker=new Node<T>(null,beginMarker,null);
beginMarker.next=endMarker;
theSize=0;
modCount++;
}
public int size(){
return theSize;
}
public boolean isEmpty(){
return size()==0;
}
public boolean add(T x){
add(size(),x);
return true;
}
public T get(int idx){
return getNode(idx).name;
}
public T set(int id,T newVal){
Node<T> p=getNode(id);
T oldVal=p.name;
p.name=newVal;
return oldVal;
}
public T remove(int id){
return remove(getNode(id));
}
private void addBefore(Node<T>p,T x){
Node<T>newnode=new Node<>(x,p.previdous,p);
newnode.previdous.next=newnode;
p.previdous=newnode;
theSize++;
modCount++;
}
private T remove(Node<T> p){
p.next.previdous=p.previdous;
p.previdous.next=p.next;
theSize--;
modCount++;
return p.name;
}
private Node<T> getNode(int id){
Node<T> p;
if (id<0||id>size())
throw new IndexOutOfBoundsException();
if (id<size()/2){
p=beginMarker.next;
for (int i = 0; i < id; i++) {
p=p.next;
}
}else {
p=endMarker;
for (int j=size();j>id;j--)
p=p.previdous;
}
return p;
}
public void add(int idx,T x){
addBefore(getNode(idx),x);
}
@Override
public Iterator<T> iterator() {
return (Iterator<T>) new LinkedListIterator();
}
private class LinkedListIterator implements Iterator<T>{
private Node<T> current=beginMarker.next;
private int expectedModCOUNT=modCount;
private boolean oktoRemove=false;
/**
* Returns {@code true} if the iteration has more elements.
* (In other words, returns {@code true} if {@link #next} would
* return an element rather than throwing an exception.)
*
* @return {@code true} if the iteration has more elements
*/
@Override
public boolean hasNext() {
return current!=endMarker;
}
@Override
public T next() {
if (modCount!=expectedModCOUNT)
throw new java.util.ConcurrentModificationException();
if (!hasNext())
throw new NoSuchElementException();
T nextItem=current.name;
current=current.next;
oktoRemove=true;
return nextItem;
}
@Override
public void remove() {
if ((modCount!=expectedModCOUNT))
throw new ConcurrentModificationException();
if (!oktoRemove)
throw new IllegalStateException();
MyLinkedList.this.remove(current.previdous);
oktoRemove=false;
expectedModCOUNT++;
}
}
}
双向链表的实现
来源:CSDN
作者:没头脑也很高兴
链接:https://blog.csdn.net/u013967394/article/details/104219736