Java学习笔记-链表及链表的操作

链表

链表是一种链式存取的数据结构,单链表中的数据是以结点的形式存在,每一个结点是由数据元素和下一个结点的存储的位置组成。单链表与数组相比的最大差别是:单链表的数据元素存放在内存空间的地址是不连续的,而数组的数据元素存放的地址在内存空间中是连续的,这也是为什么根据索引无法像数组那样直接就能查询到数据元素

结点类

public class Node {
  Object data;
  Node next;
}

链表操作

public class MyLinked {
  //存储头结点对象
  private Node head = new Node();

  /**
   * 在链表中添加结点
   *
   * @param data 要添加的结点
   */
  public void append(Object data) {
    //创建一个指针变量,用来遍历当前链表,该指针从头结点开始
    Node current = head;
    //遍历链表,直到该结点的地址为null
    while (current.next != null) {
      //将指针的地址赋值给指针
      current = current.next;
    }
    //将追加的元素封装在一个新的结点中。
    Node node = new Node();
    node.data = data;
    //将临时变量指向最后一个结点,将新建结点添加到链表末尾
    current.next = node;
  }

  /**
   * 遍历链表
   */
  public void iterate() {
    //定义 指针,遍历链表
    Node current = head;
    while (current.next != null) {
      current = current.next;
      System.out.print(current.data + " ");
    }
  }

  /**
   * 向链表中指定位置插入数据
   *
   * @param data  要插入的数据
   * @param index 插入的位置
   */
  public void insert(Object data, int index) {
    //创建计数器,用来确定插入位置
    int step = 0;
    //创建指针,遍历链表
    Node current = head;
    //循环确定要插入的位置
    while (step < index) {
      current = current.next;
      step++;
    }
    //创建新的结点,封装数据
    Node node = new Node();
    //为新的结点数据域赋值
    node.data = data;
    //将下一节点赋值给新节点的地址域
    node.next = current.next;
    //将新节点赋值给上一结点的地址域
    current.next = node;
  }

  /**
   * 按照下标返回链表中的数据元素
   *
   * @param index 下标
   */
  public Object get(int index) {
    //创建计数器,确定元素位置
    int step = 0;
    //创建指针,遍历链表
    Node current = head;
    //移动指针,确定要查找的结点
    while (step < index + 1) {
      current = current.next;
      step++;
    }
    return current.data;
  }

  /**
   * 删除指定位置的元素
   *
   * @param index 指定的下标
   */
  public void remove(int index) {
    //创建计数器,确定要删除的位置
    int step = 0;
    //创建指针,遍历数组
    Node current = head;
    //确定要删除的位置
    while (step < index) {
      current = current.next;
      step++;
    }
    //删除元素
    current.next = current.next.next;
  }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值