双向链表也叫双链表,是链表的一种 2020.04.19
题目:
双向链表
解题思路:
值得注意的是再删除的时候删除中间节点时,需要注意普通中间节点和倒数第二个中间节点要分开处理,删除时间复杂度应该是O(1),欢迎指正!
package doubly;
class Node{
Node parent = null;
Node next = null;
char contextValue;
public Node(Character contextValue){
this.contextValue = contextValue;
}
}
class LinkedList{
public Node rootNode = null;
public boolean insert(Node newNode) {
if(rootNode == null) {
rootNode = newNode;
return true;
}
Node currrentNode = rootNode;
Node parentNode = null;
while (currrentNode != null) {
parentNode = currrentNode;
currrentNode = currrentNode.next;
}
parentNode.next = newNode;
newNode.parent = parentNode;
return true;
}
public void order() {
Node currentNode = rootNode;
Node parentNode = null;
while(currentNode != null) {
System.out.print(currentNode.contextValue);
parentNode = currentNode;
currentNode = currentNode.next;
}
while(parentNode != null) {
System.out.print(parentNode.contextValue);
parentNode = parentNode.parent;
}
}
public boolean delete(Node isDeleteNode) {
Node currentNode = rootNode;
Node parentNode = null;
if(isDeleteNode == null) {
return false;
}
if(isDeleteNode == currentNode) {
rootNode = currentNode.next;
rootNode.parent=null;
return true;
}
if(isDeleteNode.next == null) {
while (currentNode.next != null) {
parentNode = currentNode;
currentNode = currentNode.next;
}
currentNode.parent = null;
parentNode.next = null;
return true;
}else {
isDeleteNode.contextValue = isDeleteNode.next.contextValue;
if(isDeleteNode.next.next != null){
isDeleteNode.next.next.parent = isDeleteNode.next.parent;
isDeleteNode.next = isDeleteNode.next.next;
return true;
}else {
isDeleteNode.next = null;
return true;
}
}
}
}
public class DoublyLinkedList {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
Node A = new Node('A');
linkedList.insert(A);
linkedList.insert(new Node('B'));
Node C = new Node('C');
linkedList.insert(C);
Node D = new Node('D');
linkedList.insert(D);
Node E = new Node('E');
linkedList.insert(E);
linkedList.order();
System.out.println();
linkedList.delete(A);
linkedList.order();
System.out.println();
// linkedList.delete(C);
// linkedList.order();
// System.out.println();
linkedList.delete(D);
linkedList.order();
System.out.println();
linkedList.delete(E);
linkedList.order();
}
}