//双向链表实现
public class TwoWayLinkedList <T>{
private Node head;
private Node last;
private int length;
private class Node{
Node pre;
Node next;
T data;
public Node(){}
public Node(Node pre, T data, Node next) {
this.pre = pre;
this.next = next;
this.data = data;
}
}
public TwoWayLinkedList(){
this.head=new Node(null,null,null);
this.last=null;
this.length=0;
}
public void add(T e) {
Node n = head;
if (length == 0) {
last = new Node(head, e, null);
head.next=last;
length++;
}
else {
//找到最后一个结点
Node oldLast=last;
//创建新节点
oldLast.next = new Node(oldLast, e, null);
last=oldLast.next;
length++;
}
}
//在i位置插入一个结点
public void insert(int i,T e){
Node n=head;
//找到第i-1个节点
for (int a = 1; a < i; a++) {
n=head.next;
}
//如果直接是在最后一个位置加结点
if (i==length+1){
last=new Node(last.pre,e,null);
length++;
}
else if(i>0&&i<length+1){
//创建新结点
Node node = new Node(n, e, n.next);
n.next.pre = node;
n.next = node;
length++;
}
}
public void clear(){
head.next=null;
length=0;
}
public void out(){
Node n=head;
for (int i = 1; i <= length; i++) {
n=n.next;
System.out.println(n.data);
}
}
}
Java双向链表实现
最新推荐文章于 2024-09-10 10:22:48 发布