public class TwoWayLinkList<T> {
private class Node {
private T item
;
private Node pre
;
private Node next
;
public Node(T item
, Node pre
, Node next
) {
this.item
= item
;
this.pre
= pre
;
this.next
= next
;
}
}
private Node head
;
private Node last
;
private int N
;
public TwoWayLinkList() {
this.head
= new Node(null
, null
, null
);
this.last
= null
;
N
= 0;
}
public void clear() {
head
.next
= null
;
last
= null
;
N
= 0;
}
public int length() {
return N
;
}
public boolean isEmpty() {
return N
== 0;
}
public T
getFirst() {
if (isEmpty()) {
return null
;
}
return head
.next
.item
;
}
public T
getLast() {
if (isEmpty()) {
return null
;
}
return last
.item
;
}
public void insert(T t
) {
if (isEmpty()) {
Node newNode
= new Node(t
, head
, null
);
head
.next
= newNode
;
last
= newNode
;
} else {
Node newNode
= new Node(t
, last
, null
);
last
.next
= newNode
;
last
= newNode
;
}
N
++;
}
public void insert(int i
,T t
){
Node pre
=head
;
for (int j
= 0; j
< i
; j
++) {
pre
=pre
.next
;
}
Node curr
=pre
.next
;
Node newNode
=new Node(t
,pre
,curr
);
curr
.pre
=newNode
;
pre
.next
=newNode
;
N
++;
}
public T
get(int i
){
Node n
= head
.next
;
for(int index
=0;index
<i
;index
++){
n
=n
.next
;
}
return n
.item
;
}
public int indexOf(T t
){
Node n
= head
;
for(int index
=0;index
<N
;index
++){
n
=n
.next
;
if (n
.item
.equals(t
)){
return index
;
}
}
return -1;
}
public T
remove(int i
){
Node pre
=head
;
for (int j
= 0; j
<i
; j
++) {
pre
=pre
.next
;
}
Node curr
=pre
.next
;
T t
=curr
.item
;
Node nextNode
=curr
.next
;
pre
.next
=nextNode
;
nextNode
.pre
=pre
;
N
--;
return t
;
}
}
public class TestTwoWayLinkList {
public static void main(String
[] args
) {
TwoWayLinkList
<String>linkList
=new TwoWayLinkList();
linkList
.insert("1");
linkList
.insert("2");
linkList
.insert(0,"0");
linkList
.insert(0,"0.5");
for (int i
= 0; i
<linkList
.length() ; i
++) {
System
.out
.println(linkList
.get(i
));
}
System
.out
.println("___________________________________");
System
.out
.println("你删除的是:"+ linkList
.remove(0));
}
}
欢迎指出不足之处。。。
转载请注明原文地址:https://ipadbbs.8miu.com/read-46978.html