单向链表JAVA实现,包括头插法与尾插法 2020.03.24
class Node{
public String contextString = null;
public Node next= null;
public Node(String contextString) {
this.contextString = contextString;
}
}
class LinkedList {
Node rootNode = null;
//尾插法
public boolean insert(Node newNode) {
if(rootNode == null) {
rootNode = newNode;
return true;
}
Node currentNode = rootNode;
Node parentNode = null;
while(currentNode != null) {
parentNode = currentNode;
currentNode = currentNode.next;
}
parentNode.next = newNode;
return true;
}
//头插法
public boolean insert2(Node newNode) {
if(rootNode == null) {
rootNode = newNode;
return true;
}
newNode.next = rootNode;
rootNode = newNode;
return true;
}
public void order() {
Node currentNode = rootNode;
while(currentNode != null) {
System.out.println("\t" + currentNode.contextString);
currentNode = currentNode.next;
}
}
public boolean delete(String deleteContext) {
Node currentNode = rootNode;
Node parentNode = null;
if(rootNode.contextString.equals(deleteContext)) {
rootNode = null;
return true;
}
while(currentNode != null) {
if(currentNode.contextString.equals(deleteContext)) {
parentNode.next = currentNode.next;
return true;
}
parentNode = currentNode;
currentNode = currentNode.next;
}
return false;
}
}
public class Linked {
public static void main(String[] args) {
LinkedList linkedList = new LinkedList();
linkedList.insert(new Node("a"));
linkedList.insert(new Node("b"));
linkedList.insert(new Node("c"));
linkedList.insert(new Node("d"));
linkedList.insert(new Node("e"));
linkedList.order();
linkedList.delete("d");
linkedList.order();
LinkedList linkedList2 = new LinkedList();
linkedList2.insert2(new Node("A"));
linkedList2.insert2(new Node("B"));
linkedList2.insert2(new Node("C"));
linkedList2.insert2(new Node("D"));
linkedList2.insert2(new Node("F"));
linkedList2.order();
linkedList2.delete("D");
linkedList2.order();
}
}