package 单链表1;
import javax.management.StandardEmitterMBean;
//我的单链表类
public class MyList {
//设置了头结点,让其数据为-2147483648即不可能的数
public Node head = new Node(-2147483648);
//初始长度为零
public int length = 0;
//内部类---节点类
public class Node {
//默认新建的节点的指针域指向null
public Node next = null;
//数据域
public int data;
public Node(int data) {
this.data = data;
}
//可直接打印单个节点数据域
@Override
public String toString() {
return "Node{" +
"data=" + data +
'}';
}
}
//头插法实现
public boolean add(int data){
Node newNode = new Node(data);
//检验分配是否成功
if (newNode == null){
return false;
}
newNode.next = head.next;
head.next = newNode;
length++;
return true;
}
//尾插法实现
public boolean addTail(int data){
Node temp = head;
//获得最后一个节点
while (temp.next != null){
temp = temp.next;
}
Node newNode = new Node(data);
temp.next = newNode;
length++;
return true;
}
//删除指定位置节点
public boolean delete(int local){
//判断合理性
if (local < 1 || local >length){
System.out.println("OVERFLOW");
return false;
}
else {
Node temp = head;
//获取要删除的节点前一个节点
for (int i = 1; i <= local - 1; i++) {
temp = temp.next;
}
//因为java有回收资源线程,不用free掉
temp.next = temp.next.next;
length--;
return true;
}
}
@Override
//自定义的直接打印单链表中的数据
public String toString() {
Node temp = head.next;
String str = "{ ";
while (temp != null){
str = str + temp.data + " ";
temp = temp.next;
}
return str + "}";
}
}
数据结构作业--单链表
最新推荐文章于 2023-08-22 09:35:49 发布