在前面我們介紹了使用Node數據結構實行單鏈表,那麼這篇博客我們來介紹一下如何實現雙向鏈表。雙向鏈表其實結構上和單鏈表非常相似,唯一的不同是構成雙向鏈表的Node中比單鏈表的Node多一個preNode數據域,preNode指向前一個Node。
- 雙向鏈表與單鏈表在特性上的比較:
- 單向鏈表,查找的方向只能是一個方向,而雙向鏈 表可以向前或者向後查找。
- 單向鏈表不能自我刪除,需要靠輔助節點 ;而雙向鏈表,則可以自我刪除 。該特性使得雙向鏈表節點的刪除更加容易。
- 在實現雙向鏈表之前我們規定:
- 頭結點不存儲數據。
- 第一個數據節點向前指向null,最後一個節點向後指向null。
- 代碼實現:
public class bidiretionalLinkList {
class Node{
private int data;
private Node preNode;
private Node postNode;
public Node(int data){
this.data = data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Node getPreNode() {
return preNode;
}
public void setPreNode(Node preNode) {
this.preNode = preNode;
}
public Node getPostNode() {
return postNode;
}
public void setPostNode(Node postNode) {
this.postNode = postNode;
}
}
private int size;
private Node headNode;
public bidiretionalLinkList(){
this.size = 0;
this.headNode = new Node(0);
}
/**
* new a node according to the data, and append it at end of linklist
* @param data
*/
public void appendNode(int data){
Node temp = this.headNode;
//find the last node.
while (temp.postNode != null){
temp = temp.postNode;
}
Node node = new Node(data);
if(temp == this.headNode){
node.setPreNode(null);
}else {
node.setPreNode(temp);
}
temp.setPostNode(node);
++ this.size;
}
/**
* delete a node according to given data
* @param data
*/
public void deleteNodeByData(int data){
if(this.headNode.getPostNode() == null)
return;
Node temp = this.headNode.getPostNode();
while (temp.getData() != data){
temp = temp.getPostNode();
}
//如果該節點是第一個節點,需要把該節點前前指向null
if(temp.getPreNode() == this.headNode){
this.headNode.setPostNode(null);
}else {
temp.getPreNode().setPostNode(temp.getPostNode());
temp.getPostNode().setPreNode(temp.getPreNode());
temp = null;
}
--this.size;
}
/**
* delete a node according to the index
* @param index
* @return, the deleted node.
*/
public Node deleteNodeByIndex(int index){
if(this.size == 0 || index > this.size || index <= 0){
return null;
}
Node temp = this.headNode;
for(int i = 0;i < index;i ++){
temp = temp.getPostNode();
}
if(temp.getPreNode() == this.headNode){
this.headNode.setPostNode(null);
}else {
temp.getPreNode().setPostNode(temp.getPostNode());
temp.getPostNode().setPreNode(temp.getPreNode());
}
--this.size;
return temp;
}
/**
* update node's data according to the node index.
* @param index
* @param data
* @return, the original data
*/
public int updateNode(int index, int data){
if(this.size == 0 || index > this.size || index <= 0){
return Integer.MIN_VALUE;
}
Node temp = this.headNode;
for(int i = 0;i < index;i ++){
temp = temp.getPostNode();
}
int tempData = temp.getData();
temp.setData(data);
return tempData;
}
}
/**
* print all nodes in the linklist
*/
public void printAllNode(){
Node temp = this.headNode;
while (temp.getPostNode() != null){
System.out.println(temp);
temp = temp.getPostNode();
}
}