对于双链表,每个节点既有前驱节点又有后继节点,在某些应用方面更加方便,对于其插入和删除需要修改两个指针,其实现的Java代码如下:
package datastructure;
public class DLLNode {
private int data;
private DLLNode next;
private DLLNode previous;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public DLLNode getNext() {
return next;
}
public void setNext(DLLNode next) {
this.next = next;
}
public DLLNode getPrevious() {
return previous;
}
public void setPrevious(DLLNode previous) {
this.previous = previous;
}
int DLLLength(DLLNode headnode) {
int length=0;
DLLNode currentnode = headnode;
while(currentnode != null) {
length++;
currentnode=currentnode.getNext();
}
return length;
}
DLLNode DLLInsert(DLLNode headnode, DLLNode nodeToInsert, int position) {
if(headnode == null) {
return nodeToInsert;
}
int size =DLLLength(headnode);
if(position > size+1 || position < 1) {
System.out.println("positon of node to insert is invalid. The valid inputs are 1 to "+(size + 1));
return headnode;
}
if(position == 1) {
nodeToInsert.setNext(headnode);
headnode.setPrevious(nodeToInsert);
return nodeToInsert;
}else {
DLLNode previousNode = headnode;
int count =1;
while(count < position -1) {
previousNode=previousNode.getNext();
count++;
}
DLLNode currentNode = previousNode.getNext();
nodeToInsert.setNext(currentNode);
if(currentNode != null) {
currentNode.setPrevious(nodeToInsert);
}
previousNode.setNext(nodeToInsert);
nodeToInsert.setPrevious(previousNode);
}
return headnode;
}
DLLNode DLLDelete(DLLNode headnode, int position) {
int size =DLLLength(headnode);
if(position > size+1 || position < 1) {
System.out.println("positon of node to insert is invalid. The valid inputs are 1 to "+(size + 1));
return headnode;
}
if(position == 1) {
DLLNode currentNode = headnode.getNext();
headnode = null;
currentNode.setPrevious(null);
return currentNode;
}else {
DLLNode perviousNode = headnode;
int count = 1;
while(count < position -1) {
perviousNode = perviousNode.getNext();
count++;
}
DLLNode currentNode = perviousNode.getNext();
DLLNode laterNode = currentNode.getNext();
perviousNode.setNext(laterNode);
if(laterNode != null) {
laterNode.setPrevious(perviousNode);
currentNode=null;
}
return headnode;
}
}
}
双向链表的插入和删除稍微麻烦一点,代码如上!