class Node {
public int val;
public Node next;
//有参构造方法
public Node(int val) {
this.val = val;
this.next = null;
}
}
class LinkList {
public Node head;//定义首结点
public Node tail;//定义尾结点
public int size;//记录插入的结点数量
//尾插法添加结点
public void append(int val) {
Node node = new Node(val);
if (this.head == null) {
head = tail = node;
size++;
} else {
tail.next = node;
tail = node;
size++;
}
}
//写一个插入函数
public void insert(int index, int val) {
//首先判断链表是否为空 || 如果index大于size,无法插入
if (this.head == null || index > size || index <= 0) {
return;
}
size++;
Node node = new Node(val);
Node cur = this.head;
//查找index前一个节点结点
for (int i = 2; i < index; i++) {
cur = cur.next;
}
node.next = cur.next;
cur.next = node;
if (index == 1) {
//交换值
node.val += cur.val;
cur.val = node.val - cur.val;
node.val -= cur.val;
}
}
//删除函数
public void delete(int index) {
//首先判断链表是否为空 || 如果index大于size,无法删除
if (this.head == null || index > size || index <= 0) {
return;
}
//如果要删除的是首节点
if (index == 1) {
head = head.next;
}
Node cur = this.head;
//查找到index前一个节点
for (int i = 1; i < index; i++) {
cur = cur.next;
}
cur.next = cur.next.next;
size--;
}
//获取第index个节点的值
public int get(int index) {
Node node = this.head;
for (int i = 1; i < index; i++) {
node = node.next;
}
return node.val;
}
//打印链表方法
public void display() {
Node node = this.head;
while (node != null) {
System.out.println(node.val);
node = node.next;
}
}
//打印链表长度
public int length() {
return size;
}
}
public class MyLinkList {
public static void main(String[] args) {
//测试部分
LinkList linkList = new LinkList();
linkList.append(1);
linkList.append(3);
linkList.append(5);
linkList.append(7);
linkList.append(9);
linkList.insert(1, 99);
linkList.display();
System.out.println("---------------");
System.out.println("当前链表长度 " + linkList.get(1));
System.out.println("删除第一个元素");
linkList.delete(1);
System.out.println("获取第一个值 " + linkList.get(1));
System.out.println("当前链表长度 " + linkList.length());
}
}
java单链表
于 2023-05-16 11:36:31 首次发布