输入 一组数据 8 3 10 1 6 14 4 7 3
用 java 模拟链表 进行 输入 删除 和 输出
// java 代码实现 链表 模拟
public class Linklist {
private Node root;
// 添加节点
public void addNode(String name){
if(root == null){
root = new Node(name);
}
else{
root.addNode(name);
}
}
// 删除节点
public void deleteNode(String name){
if(root.name.equals(name)){
root = root.next;
}
else{
root.deleteNode(name);
}
}
// 打印节点
public void printNode(){
if(root != null){
root.printNode();
}
}
// 节点
class Node{
private Node next;
private String name;
public Node(String name) {
this.name = name;
}
public void addNode(String name){
if(this.next == null){
this.next = new Node(name);
}
else{
this.next.addNode(name);
}
}
public void deleteNode(String name){
if(this.next != null){
if(this.next.name.equals(name)){
this.next = this.next.next;
this.next.deleteNode(name);
}
else{
this.next.deleteNode(name);
}
}
}
public void printNode(){
System.out.println(this.name);
if(this.next != null){
this.next.printNode();
}
}
}
public static void main(String[] args) {
// 模拟链表
Linklist link = new Linklist();
link.addNode("8");
link.addNode("3");
link.addNode("10");
link.addNode("6");
link.addNode("14");
link.addNode("4");
link.addNode("7");
link.addNode("3");
//删除某个节点
link.deleteNode("3");
// 打印所有的节点
link.printNode();
}
}