public class Main {
public static void main(String[] args) {
LNode L = new LNode();
System.out.println(L.number());
L.Isempty();
L.addFirst(4);//头插
L.addFirst(3);
L.addFirst(2);
L.addFirst(1);
L.addLast(5);//尾插
L.check();
LNode.Node L1 = L.findLast();//最后一个结点
System.out.println();
System.out.println(L1.value);
LNode.Node L2 = L.indexcheck(0);//指定索引查询
if (L2 == null) {
System.out.println("未查询到指定索引");
} else {
System.out.println(L2.value);
}
int i = L.valuecheck(1);
if (i == -1) {
System.out.println("不存在指定元素");
} else {
System.out.println("存在该元素,索引为" + i);
}
System.out.println("链表大小" + L.number());
L.removeIndex(0);
L.removeValue(2);
L.insertIndex(0, 2);
L.insertIndex(4, 6);
L.check();
}
public static class LNode {
private Node head = null;//头指针
public class Node {
int value;
Node next;
public Node(int value, Node next) {
this.value = value;
this.next = next;
}
}
//头插
public void addFirst(int value) {
if (head == null) {
head = new Node(value, null);
} else {
head = new Node(value, head);
}
}
//尾插
public void addLast(int value) {
Node node = findLast();
if (node == null) {
addFirst(value);
return;
}
node.next = new Node(value, null);
}
//找最后一个节点
public Node findLast() {
if (head == null) {
return null;
}
Node p;
for (p = head; p.next != null; p = p.next) {
}
return p;
}
//遍历
public void check() {
if (head == null) {
System.out.println("空链表");
return;
}
for (Node p = head; p != null; p = p.next) {
System.out.print(p.value + " ");
}
}
//根据索引查找元素
public Node indexcheck(int index) {
int i = -1;
for (Node p = head; p != null; p = p.next) {
i++;
if (i == index) {
return p;
}
}
return null;
}
//返回链表大小
public int number() {
int i = 0;
for (Node p = head; p != null; p = p.next) {
i++;
}
return i;
}
//查找指定值
public int valuecheck(int value1) {
int i = -1;
for (Node p = head; p != null; p = p.next) {
i++;
if (p.value == value1) {
return i;
}
}
return -1;
}
//删除指定索引元素
public void removeIndex(int index) {
int i = -1;
if (head == null) {
System.out.println("空链表");
return;
}
if (index > number() - 1) {
System.out.println("索引不存在");
return;
}
if (index == 0) {
head = head.next;
return;
}
for (Node p = head; p != null; p = p.next) {
i++;
if (index - 1 == i) {
p.next = p.next.next;
return;
}
}
}
//删除指定值元素
public void removeValue(int value1) {
int i = -1;
int j = 0;
if (head == null) {
System.out.println("空链表");
return;
}
for (Node p = head; p != null; p = p.next) {
i++;
if (value1 == p.value) {
j++;
removeIndex(i);
}
}
if (j == 0) {
System.out.println("该值不存在");
}
}
//按索引插入指定值
public void insertIndex(int index, int value) {
int i = -1;
if (head == null) {
System.out.println("空链表");
return;
}
if (index == 0) {
addFirst(value);
return;
}
if (index == number()) {
addLast(value);
return;
}
for (Node p = head; p != null; p = p.next) {
if (i == index - 1) {
p.next = new Node(value, p.next);
return;
}
}
System.out.println("插入失败,没有指定索引");
}
//判空
public void Isempty() {
if (head == null) {
System.out.println("空链表");
} else {
System.out.println("非空链表");
}
}
}
}