public class TestLinkList {
public static void main(String[] args) {
NodeManager nm = new NodeManager();
System.out.println("初始化链表节点");
nm.add(5);
nm.add(4);
nm.add(3);
nm.add(2);
nm.add(1);
nm.showNodes();
System.out.println("删除节点之后");
nm.delete(3);
nm.showNodes();
System.out.println("修改结点之后");
nm.update(5, 6);
nm.showNodes();
System.out.println("寻找节点");
System.out.println(nm.find(2));
}
}
class NodeManager{
private Node root;
public void add(int data) {
if(root==null) {
root = new Node(data);
}
else {
root.addNode(data);
}
}
public void delete(int data) {
if(root!=null) {
if(root.getData()==data) {
root = root.next;
}
else {
root.delNode(data);
}
}
}
public void update(int oldData,int newData) {
if(root!=null) {
if(root.getData()==oldData) {
root.setData(newData);
}
else {
root.updateNode(oldData, newData);
}
}
}
public boolean find(int data) {
if(root==null) {
return false;
}
return root.findNode(data);
}
public void showNodes() {
if(root!=null) {
System.out.println(root.data+" ");
root.printNodes();
}
else {
System.out.println("当前链表没有存储内容");
}
}
public void showNodes2()
{
root.printNodes2();
}
//节点类,由内部类实现。最好不用内部类。
private class Node{
private int data;
private Node next;
public Node(int data) {
this.data = data;
}
public int getData() {
return this.data;
}
public void setData(int data) {
this.data = data;
}
//添加节点
public void addNode(int data) {
if(this.next==null) {
this.next = new Node(data);
}
else {
this.next.addNode(data);
}
}
//删除节点
public void delNode(int data) {
if(this.next.getData()==data) {
this.next = this.next.next;
}
else {
this.next.delNode(data);
}
}
//修改节点
public void updateNode(int oldData,int newData) {
if(this.next.getData()==oldData) {
this.next.setData(newData);
}
else {
this.next.updateNode(oldData, newData);
}
}
//寻找节点
public boolean findNode(int data) {
if(this.getData()==data) {
return true;
}
else {
if(this.next!=null) {
return this.next.findNode(data);
}
}
return false;
}
//打印节点
public void printNodes() {
if(this.next!=null) {
System.out.println(this.next.data+" ");
this.next.printNodes();
}
}
//非递归方式打印节点
public void printNodes2() {
Node temp = this;
while(temp!=null) {
System.out.println(temp.data);
temp = temp.next;
}
}
}
}