**
* 实现的简单链表
* @author zcl
*
*/
public class LinkedList {
public class Node {
private String nodeName;
private Node next;
public Node(String name) {
nodeName = name;
}
public Node(String name, Node next) {
this(name);
this.next = next;
}
/**
* 添加一个节点
* @param node
*/
public void addNode(Node node) {
if (this.next == null) {//若当前的节点的下一节点为空
this.next = node;
} else { //递归调用当前节点的下一点的AddNode()
this.next.addNode(node);
}
}
public void updateNode(String oldName, String newName) {
if (this.nodeName.equals(oldName)) {
this.nodeName = newName;
} else {
if (this.next != null) {
this.next.updateNode(oldName, newName);
}
}
}
public void delNode(Node preNode, String name) {
if (this.nodeName.equals(name)) {
preNode.next = this.next;
} else {
if (this.next != null) {
this.next.delNode(this, name);
} else {
throw new RuntimeException("没有找到[" + name + "]节点");
}
}
}
public void printNode() {
System.out.print(nodeName + "-->");
if (this.next != null) {
this.next.printNode();
}
}
}
private Node root = new Node("");//根节点设置为空
//添加新节点
public void add(Node newNode) {
root.addNode(newNode);
}
/**
* 修改节点
* @param pos 在修改节点的位置
* @param newNode
*/
public void update(int pos, String newName) {
Node newNode = new Node(newName);
Node preNode = getNode(pos-1);
Node node = getNode(pos);
if (preNode == null || node == null) {
throw new RuntimeException("没有找到特定的节点");
}
preNode.next = newNode;
newNode.next = node.next;
}
/**
* 更新节点的名称
* @param oldName
* @param newName
*/
public void update(String oldName, String newName) {
if (root.next != null)
root.next.updateNode(oldName, newName);
}
/**
* 删除特定名称的节点
* @param name
*/
public void del(String name) {
if (root.next != null)
root.next.delNode(root, name);
}
public void print() {
if (root.next != null)
root.next.printNode();
}
/**
* 得到某一位置的节点
* @param pos
* @return
*/
public Node getNode(int pos) {
Node node = root;
for (int i=1; i<=pos && node != null; i++) {
node = node.next;
}
return node;
}
public static class Test {
public static void main(String[] args) {
LinkedList list = new LinkedList();
list.add(list.new Node("第一节点"));
list.add(list.new Node("第二节点"));
list.add(list.new Node("第三节点"));
list.add(list.new Node("第四节点"));
list.add(list.new Node("第五节点"));
list.add(list.new Node("第六节点"));
list.print();
System.out.println();
list.update("第一节点", "xxx");
list.print();
System.out.println();
list.del("第五节点");
list.del("xxx");
list.print();
System.out.println();
System.out.println(list.getNode(2).nodeName);
list.update(2, "abc");
list.print();
}
}
}
打印的结果:
第一节点-->第二节点-->第三节点-->第四节点-->第五节点-->第六节点-->
xxx-->第二节点-->第三节点-->第四节点-->第五节点-->第六节点-->
第二节点-->第三节点-->第四节点-->第六节点-->
第三节点
第二节点-->abc-->第四节点-->第六节点-->
1697

被折叠的 条评论
为什么被折叠?



