单链表实现

单链表实现

//节点定义
@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;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值