public class LinkedList<E> {
//结点类
private class Node{
public E e;
public Node next;
public Node(E e,Node next){
this.e=e;
this.next=next;
}
public Node(E e){
this(e,null);
}
public Node(){
this(null,null);
}
@Override
public String toString() {
return e.toString();
}
}
//虚拟头结点
private Node dummyHead;
private int size;
public LinkedList(){
dummyHead=new Node(null,null);
size=0;
}
//获取元素个数
public int getSize(){
return size;
}
//判断是否为空
public boolean isEmpty(){
return size==0;
}
//在链表头添加新的元素
public void addFirst(E e){
// Node node = new Node(e);
// node.next=head;
// head=node;
add(0,e);
}
//在链表中间添加元素,找到待添加节点的前一个节点,修改指针
public void add(int index,E e){
if (index<0||index>size){
throw new IllegalArgumentException("Add failed.Illegal index.");
}
if (index==0){
addFirst(e);
}else {
Node prev=dummyHead;
for (int i = 0; i < index; i++) {
//向前移动,找到索引前一个节点
prev=prev.next;
}
// Node node = new Node(e);
// node.next=prev.next;
// prev.next=node;
prev.next=new Node(e,prev.next);
size++;
}
}
public void addLast(E e){
add(size,e);
}
}
链表的虚拟头结点
最新推荐文章于 2024-10-03 13:35:46 发布