Java单链表的使用

渡星河
2022-11-21 / 0 评论 / 9 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月21日,已超过665天没有更新,若内容或图片失效,请留言反馈。

太懒了,不想写注释,直接给你们看老师的吧

//测试类
public class TestSingleList {
  public static void main(String[] args) {
    SingleList.addTail(100);
    SingleList.addTail(1000);
    System.out.println("size : " + SingleList.size);
  }
}

//单链表数据模型类
class SingleList {
  //头节点
  static Node first = null;
  //尾节点
  static Node last = null;
  //节点数
  static int size = 0;

  //添加-尾部
  //value表示要存入节点数据域的值。
  public static void addTail(int value) {
    //创建一个节点
    Node newNode = new Node();
    newNode.data = value;
    if (last == null) {
      first = newNode;
      last = newNode;
    } else {
      last.next = newNode;
      last = newNode;
    }
    size++;
  }
  //添加-头部
  public static void addFirst(int value) {
    //创建一个节点
    Node newNode = new Node();
    newNode.data = value;
    if(first == null) {
      first = newNode;
      last = newNode;
    } else {
      newNode.next = first;
      first = newNode;
    }
    siez++;
  }
    //删除,position表示要删除的是第几个节点
  public static void remove(int position) {
    //记录当前访问到了第几个节点
    int count = 1;
    //变量指向当前节点的上一个节点
    Node preCurrent = null;
    //定义变量指向需要查找的当前节点
    Node current = first;
    while(current != null) {
      //当删除的是第一个节点时
      if (position == 1) {
        first = first.next;
        current.next = null;
        return;
      } else if(position == count) {
        System.out.println("执行删除");
        preCurrent.next = current.next;
        current.next = null;//断掉引用
        return;
      } else {
        preCurrent = current;
        current = current.next;
      }
      count++;
    }
  }
   //更新, 把指定位置position的值更新为新的值newVal
  public static void update(int position, int newVal){
    Node node = get(position);
    node.data = newVal;
  }

  //查找,按照位置访问
  public static Node get(int position){
    int count = 1;
    Node t = first;
    while(t != null) {
      if (position == count) {
        System.out.println(t.data);
        return t;
      }
      t = t.next;
      count++;
    }
    return null;
  }

  //查看链表中是否包含指定的值val
  public static void containes(int val){}
  //反转
  public static void reverseList(){}
  //在指定位置插入一个节点
  public static void insert(int position, int value) {}
  //遍历链表
  public static void traverse() {
    //定义一个临时变量用于获取节点的数据
    Node t = first;
    while(t != null) {
      System.out.println(t.data);
      t = t.next;
    }
  }
}

//节点类
class Node {
  int data;
  Node next;
}
1

评论 (0)

取消