单链表实现
//节点定义
@NoArgsConstructor
@ToString
public class Node {
public int value;
public int order;
public Node next;
public Node(int value, int order) {
this.value = value;
this.order = order;
}
}
//链表实现
public class SingleList {
//虚拟头节点
private static Node head = new Node(0, 0);
//添加节点
public static void add(Node node) {
Node cur = head;
while (true) {
if (null == cur.next) {
cur.next = node;
break;
} else {
cur = cur.next;
}
}
}
//删除节点 未考虑重复
public static void delete(int value) {
if (isEmpty()) {
throw new RuntimeException("链表为空");
}
Node cur = head;
while (true) {
if (null == cur.next) {
throw new RuntimeException("未找到该节点");
}
if (cur.next.value == value) {
cur.next = cur.next.next;
break;
}
cur = cur.next;
}
}
//修改节点
public static void update(Node node) {
Node cur = head;
while (true) {
if (null == cur.next) {
throw new RuntimeException("未找到该节点");
}
if (cur.next.value == node.value) {
node.next = cur.next.next;
cur.next = node;
break;
}
cur = cur.next;
}
}
//按顺序(node.order大小)进行添加
public static void addByOrder(Node node) {
Node cur = head;
if (null == cur.next) {
cur.next = node;
} else {
while (true) {
if (null == cur.next) {
cur.next = node;
break;
}
int pre = cur.order;
int after = cur.next.order;
if (node.order < after && node.order > pre) {
Node mid = cur.next;
cur.next = node;
node.next = mid;
break;
}
cur = cur.next;
}
}
}
public static Boolean isEmpty() {
return null == head.next;
}