【Java】SinglyLinkedListSentinel 带哨兵的单链表

哨兵

类属性

private Node head = new Node(Integer.MIN_VALUE, null);

头节点指向的是哨兵,哨兵的值可以设置为无穷小,初始的 next 设置为 null

这样一来,在后续过程中就不用再判断链表是否为空,因为带哨兵的链表永远是非空

节点类(与无哨兵的单链表相同)

private static class Node {
        private int value;
        private Node next;

        public Node(int value, Node next) {
            this.next = next;
            this.value = value;
        }
    }

addFirst(int value)方法

public void addFirst(int value) {
        head = new Node(value, head);
    }

直接插入,而无需判断链表是否为空

addLast(int value)方法

public void addLast(int value) {
        Node last = head;
        while (last.next != null)
            last = last.next;
        last.next = new Node(value, null);
    }

同样也删去了判断

遍历

public void loop() {
        Node curr = head.next;
        while (curr != null) {
            System.out.println(curr.value);
            curr = curr.next;
        }
    }

注意的是,遍历要从头节点的下一个节点开始(因为头节点指向的是哨兵)

insert(int index, int value)方法

public void insert(int index, int value) {
        Node prev = head.next;
        for (int i = 0; prev != null; prev = prev.next, i++) {
            if (index - 1 == i) {
                break;
            }
        }
        prev.next = new Node(value, prev.next);
    }

remove(int index)方法

public void remove(int index) {
        Node prev = head.next;
        for (int i = 0; prev != null; prev = prev.next, i++) {
            if (index - 1 == i) {
                break;
            }
        }
        prev.next = prev.next.next;
    }

注意插入和删除都是要从头节点的下一个节点开始

  • 10
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值