单链

  • 数据域data:存储数据元素信息的域称为数据域;
  • 指针域:存储直接后继位置的域称为指针域;指针域中存储的信息称为指针或链。
  • 数据域和指针域组成数据元素ai的存储印象,称为节点(Node).
  • 每个节点中包含一个指针域,称为单链表。
  • 链表中第一个节点的存储的位置称为头指针。
  • 链表的最后一个节点指针为“空”。
  • 单链表的第一个节点前附设一个节点,称为头结点。
  • 头结点和头指针的异同
    在这里插入图片描述
  • 头插入:
class TestLink {
    class Entry {   //节点Entry
        int data;
        Entry next;

        public Entry() {   //头结点
            this.data = -1;  //头结点的data域不放数据
            this.next = null;
        }

        //数据节点
        public Entry(int val) {
            this.data = val;
            this.next = null;
        }
    }

    private Entry head;  //头引用

    public TestLink() {
        this.head = new Entry();
    }
    //头插入
    public void insertHead(int val) {
        Entry cur = new Entry();
        cur.next = this.head.next;
        this.head.next = cur;
    }
  • 尾插入
public void insertTail(int val) {
    //得到尾巴
    Entry cur = this.head;  //定义一个cur代替头结点
    while (cur.next != null) {
        cur = cur.next;
    }
    //插入数据
    Entry entry = new Entry(val);
    cur.next = entry;
}
  • 任意位置插入
//得到单链表的长度(数据节点的个数)
public int getLength() {
    int count = 0;
    Entry cur = this.head.next;
    while(cur != null) {
        count ++;
        cur = cur.next;
    }
    return count;
}
//任意位置插入
public void insertPos(int val, int pos) {
    if (pos < 0 || pos > getLength()) {
        return;
}
    Entry cur = this.head;   //定义一个cur代替头结点
    for (int i = 0; i < pos - 1;i ++) {
        cur = cur.next;
    }
        Entry entry = new Entry(val);
        entry.next = cur.next;
        cur.next = entry;
    }
    public void show() {
    Entry cur = this.head.next;  //头结点的data域不放数据  所以从头结点的写一个节点开始打印
    while(cur != null) {
        System.out.println(cur.data + " ");
    }
    System.out.println();

}
}

在这里插入图片描述

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值