1. 结构定义:
public class LinkedList<E> {
private int size
;
private Node
<E> first
;
static final int ELEMENT_NOT_FOUND
= -1;
private static class Node<E> {
E element
;
Node
<E> next
;
public Node(E element
, Node
<E> next
) {
this.element
= element
;
this.next
= next
;
}
public void clear();
public int size();
public boolean isEmpty();
public boolean contains(E element
);
public int indexOf(E element
);
private Node
<E> node(int index
);
public void add(E element
);
public E
get(int index
);
public E
set(int index
, E element
);
public void add(int index
, E element
);
public E
remove(int index
);
}
2. 清空元素
public void clear(){
size
= 0;
first
= null
;
}
3. 获取元素个数
public int size(){
return size
;
}
4.是否为空
public boolean isEmpty(){
return size
== 0;
}
5.查看元素的索引
public int indexOf(E element
){
if(element
== null
){
Node
<E> node
= first
;
for(int i
= 0; i
< size
; i
++){
if(node
.element
== null
) return i
;
node
= node
.next
;
}
} else{
Node
<E> node
= first
;
for(int i
= 0; i
< size
; i
++){
if(element
.equals(node
.element
)) return i
;
node
= node
.next
;
}
}
return ELEMENT_NOT_FOUND
;
}
6.是否包含某个元素
public boolean contains(E element
){
return indexOf(element
) != ELEMENT_NOT_FOUND
;
}
7.获取index位置对应的节点对象
private Node
<E> node(int index
){
if (index
< 0 || index
>= size
) {
throw new IndexOutOfBoundsException("Index:" + index
+ ", Size:" + size
);
}
Node
<E> node
= first
;
for(int i
= 0; i
< index
; i
++ ){
node
= node
.next
;
}
return node
;
}
8.获取index位置的元素
public E
get(int index
){
return node(index
).element
;
}
9.设置index位置的元素
public E
set(int index
, E element
){
Node
<E> node
= node(index
);
E old
= node
.element
;
node
.element
= element
;
return old
;
}
10.在index位置插入一个元素
public void add(int index
, E element
){
if (index
< 0 || index
> size
) {
throw new IndexOutOfBoundsException("Index:" + index
+ ", Size:" + size
);
}
if(index
== 0){
first
= new Node<E>(element
, first
);
}else{
Node
<E> prev
= node(index
-1);
prev
.next
= new Node<E>(element
, prev
.next
);
}
size
++;
}
11.添加元素到尾部
public void add(E element
){
add(size
,element
);
}
12.删除index位置的元素
public E
remove(int index
){
if (index
< 0 || index
>= size
) {
throw new IndexOutOfBoundsException("Index:" + index
+ ", Size:" + size
);
}
Node
<E> node
= first
;
if(index
== 0){
first
= first
.next
;
} else{
Node
<E> prev
= node(index
-1);
node
= prev
.next
;
prev
.next
= node
.next
;
}
size
--;
return node
.element
;
}
转载请注明原文地址:https://tech.qufami.com/read-3246.html