类:节点类,单链表类
实现方法:添加节点,插入节点,删除节点
public class Node {
private int data;// 节点的值
public Node next;// 指向下一个节点的指针
public Node(int data) {// 初始化head
this.data = data;
this.next = null;
}
public Node(int data, Node next) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
public class MyList { private Node head = null;//定义头节点 private int nodeNum = 0;//记录节点数目 //添加元素 public void append(Node x){ if(head == null){ head = x; }else{ Node node = head; while(node.next != null){ node = node.next; } node.next = x; } nodeNum ++; } //插入元素 public void insert(Node x,int index){ if(index < nodeNum){ nodeNum ++; Node node = head; for(int i = 1;i<=index-2;i++){ node = node.next; } x.next = node.next; node.next = x; } } //删除元素 public void delete(Node x){ nodeNum -- ; Node node = null; for(node = this.getHead();node != null ; node = node.next){ if(node.next != null && node.next.getData() == x.getData()){ if (node.next.next != null) { node.next = node.next.next; } else { node.next = null; } } } } //打印列表 public void show(){ Node node = null; for(node = this.getHead();node != null ; node = node.next){ System.out.println(node.getData()); } } public Node getHead(){ return head; } public int getNodeNum(){ return nodeNum; } public static void main(String[] args){ MyList myList = new MyList(); Node node_1 = new Node(1); Node node_2 = new Node(2); Node node_3 = new Node(3); Node node_4 = new Node(4); Node node_5 = new Node(5); myList.append(node_1); myList.append(node_2); myList.append(node_3); myList.append(node_4); myList.append(node_5); myList.show(); System.out.println("-----------------------"); Node node_6 = new Node(6); Node node_7 = new Node(7); myList.insert(node_6,3); myList.insert(node_7, 4); myList.show(); System.out.println("-----------------------"); myList.delete(node_7); myList.show(); // System.out.println(myList.getNodeNum()); }}
结果可以正常输出