https://www.cnblogs.com/llfy/p/9395936.html
package train.demo;
public class MyLink {
Node head = null;
class Node {
Node next = null;
int data;
public Node(int data) {
this.data = data;
}
}
// 向链表中插入数据
public void addNode(int d) {
Node newNode = new Node(d);
if (head == null) {
head = newNode;
return;
}
Node tmp = head;
while (tmp.next != null) {
tmp = tmp.next;
}
tmp.next = newNode;
}
// 删除第i个节点
public boolean deleteNode(int index) {
if (index < 1 || index > length()) {
return false;
}
if (index == 1) {
head = head.next;
return true;
}
int i = 1;
Node preNode = head;
Node curNode = preNode.next;
while (curNode != null) {
if (i == index) {
preNode.next = curNode.next;
return true;
}
preNode = curNode;
curNode = curNode.next;
i++;
}
return false;
}
public int length(){
int length = 0;
Node tmp = head;
while (tmp != null) {
length++;
tmp = tmp.next;
}
return length;
}
// 打印链表
public void display() {
System.out.println("打印链表");
Node tmp = head;
while (tmp != null) {
System.out.println(tmp.data);
tmp = tmp.next;
}
}
public static void main(String[] args) {
MyLink list = new MyLink();
list.addNode(0);
list.addNode(1);
list.addNode(2);
list.addNode(3);
list.addNode(4);
System.out.println("长度:" + list.length());
list.display();
list.deleteNode(1);
list.display();
}
}
网友评论