学习JAVA,练练手,写了一个双向链表。写的不好,还请朋友指教。
首先要写一个节点对象:
public class Node {
public Node previous;
public Node next;
private Object value;
public Node(Object data){
this.value = data;
this.next = null;
this.previous = null;
}
}
接着是我们这次的主角,链表对象。
public class List {
private Node head;
private Node tail;
private int size;
public void reset(){
head = null;
tail = null;
size = 0;
}
//在链表的最后添加一个节点
public void addNode(Object obj){
Node node = new Node(obj);
if(size ==0){
head = node;
tail = node;
}
else{
node.previous = tail;
tail.next = node;
node.next = null;
tail = node;
}
size++;
}
//在链表的某个位置插入一个对象,第一个节点之前的位置为0
public void insertNode(Object obj,int position){
if(position<0 || position>size){
System.out.println("insert position is out of band!");
return;
}
Node node = new Node(obj);
if(size ==0){
head = node;
tail = node;
}
else if(position == 0){
node.next = head;
node.next.previous = node;
head = node;
}
else{
Node current = head;
for(int i = 1;i<position;i++){
current = current.next;
}
node.previous = current;
node.next = current.next;
if(position == size){
current.next = node;
tail = node;
}
else {
current.next.previous = node;
current.next = node;
}
}
size++;
}
//删除一个节点
public void deleteNode(int position){
if(position <= 0 || position >size){
System.out.println("delete position is out of band!");
return;
}
Node current = head;
if(position ==1){
if(size == 1){
head = null;
tail = null;
}
else{
head = current.next;
current.next.previous = null;
}
}
else{
for(int i = 1;i<position;i++){
current = current.next;
}
if(position == size){
tail = current.previous;
tail.next = null;
}
else{
current.previous.next = current.next;
current.next.previous = current.previous;
}
}
current.next = null;
current.previous = null;
size--;
}
}