您的位置:首页 > 编程语言 > Java开发

Java实现双链表

2014-07-27 13:48 148 查看
public class DoubleLink<T> {
//存放第一个指针
private Node<T> firstNode;
//存放最后一个指针
private Node<T> lastNode;
//存放链大小
private int size;

//构造函数
public DoubleLink() {}

// --------------------------------add()系列----------------------------------
public void addFirst(T data) {
linkFirst(data);

}

public void addLast(T data) {
linkLast(data);
}

public void add(T data) {
linkLast(data);
}

public void linkFirst(T data) {
Node f = this.firstNode;
Node newNode = new Node<T>(data, f, null);
this.firstNode = newNode;
if (f == null) {
// 1 如果等于空,说明他没有前一个Node
// 2 如果等于空,说明这是一张空链表,所以此时,this.lastNode=newNode,即:链的最后一个和第一个重合
this.lastNode = this.firstNode;
} else {
// 1 如果不等于空,说明存在firsrNode链表
f.prev = this.firstNode;
}
this.size++;
}

public void linkLast(T data) {
if (this.firstNode == null) {
linkFirst(data);
return;
}
// 如果链中不是为空,那么就有firstNode,lastNode
Node newNode = new Node<T>(data, this.lastNode, null);
this.lastNode.next = newNode;
this.lastNode = newNode;
this.size++;
}

// --------------------------------remove()系列--------------------------------
public T removeFirst() {
if (this.firstNode == null) {
return null;
}
//记录返回数据
T data = this.firstNode.data;

// 删除过程

Node nowFirstNode = this.firstNode.next;

//先将原先fisrtNode中的数据清空
this.firstNode.data=null;
this.firstNode.next=null;

if (nowFirstNode == null) {
//如果为空,说明链中只有1个元素
//将引用置空
this.firstNode=null;
this.lastNode = null;
} else {
this.firstNode = nowFirstNode;
}
// 将被删除的元素返回
this.size--;
return data;
}

public T removeLast() {
if (this.firstNode == null) {
return null;
}
T t=this.lastNode.data;
Node nowLastNode = this.lastNode.prev;

this.lastNode.data=null;
this.lastNode.prev=null;
this.lastNode=null;

if (nowLastNode == null) {
// 如果等于空, 那说明这张链中只有一个元素,即:this.firstNode 和 this.lastNode 都是指向同一个内存地址
// 让垃圾回收机制,回收这些没有引用的垃圾(原先被firstNode 中的 data--->"内容1" next---->"内容2"
// prev-->"内容3")
this.firstNode=null;
} else {
//如果不等于空, 那就说明链表中存在》=2以上的元素个数
//清除this.lastNode 中  data ,prev ;

nowLastNode.next=null;
this.lastNode = nowLastNode;
}
this.size--;
return t;
}

public T remove() {
return removeLast();
}

// --------------------------------get()系列----------------------------------
public T get(int index) {
if (index < 0 || index >= this.size) {
throw new RuntimeException("下标: ‘" + index + "’ 溢出!");
}
Node node = firstNode;
for (int i = 0; i < index; i++) {
node = node.next;
}
return (T) node.data;
}

public void show() {
Node node = this.firstNode;
while (node != null) {
System.out.println(node.data + "\t");
node = node.next;
}
}

public Node<T> getFirstNode() {
return firstNode;
}

public Node<T> getLastNode() {
return lastNode;
}

class Node<T> {
Node next;
Node prev;
T data;

Node(T data, Node prev, Node next) {
this.data = data;
this.prev = prev;
this.next = next;
}
}

public int getSize() {
return this.size;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java 数据