java--数据结构

Java 中常见的数据结构类型包括以下几种:

  1. 数组(Array):一组有序的数据元素,可以通过下标来访问元素。例如:

      int[] numbers = {1, 2, 3, 4, 5}; System.out.println(numbers[0]); // 输出 1

  1. 链表(Linked List):一组通过指针相连的节点,每个节点包含一个数据元素和指向下一个节点的指针。例如:

      class Node {

        int data; Node next; public Node(int data) {

          this.data = data; this.next = null;

         } }

         Node head = new Node(1);

           head.next = new Node(2);

           head.next.next = new Node(3);

        }

  1. 栈(Stack):一种先进后出(Last-In-First-Out,LIFO)的数据结构,只允许在栈顶进行插入和删除操作。例如:

   Stack<Integer> stack = new Stack<>();

   stack.push(1); stack.push(2);

   stack.push(3);

    System.out.println(stack.pop()); // 输出 3

  1. 队列(Queue):一种先进先出(First-In-First-Out,FIFO)的数据结构,允许在队尾进行插入操作,在队头进行删除操作。例如:

   Queue<Integer> queue = new LinkedList<>();

   queue.offer(1); queue.offer(2);

   queue.offer(3);

   System.out.println(queue.poll()); // 输出 1

  1. 树(Tree):一种由节点和边组成的层次结构,每个节点可以有多个子节点。例如:

   class TreeNode {

    int val; TreeNode left;

    TreeNode right;

     public TreeNode(int val) {

         this.val = val; 

         this.left = null;

         this.right = null;

    } }

    TreeNode root = new TreeNode(1);

    root.left = new TreeNode(2);

    root.right = new TreeNode(3);

除了我之前提到的数据结构,Java 中还有以下常见的数据结构:

  1. 哈希表(Hash Table):一种通过哈希函数将键映射到值的数据结构,可以快速地进行插入、查找和删除操作。例如:

    Map<String, Integer> map = new HashMap<>();

    map.put("apple", 1);

    map.put("banana", 2);

    map.put("orange", 3);

    System.out.println(map.get("apple")); // 输出 1

  1. 堆(Heap):一种可以快速找到最大值或最小值的数据结构,通常用于实现优先队列。例如:

    PriorityQueue<Integer> maxHeap = new PriorityQueue<(Collections.reverseOrder());

    maxHeap.offer(1);

    maxHeap.offer(3);

    maxHeap.offer(2);

    System.out.println(maxHeap.poll()); // 输出 3

  1. 图(Graph):一种由节点和边组成的非线性数据结构,用于表示各种关系。例如:

    class Graph {

      int V;

      List<Integer>[] adj; 

      public Graph(int V) {

        this.V = V;

        adj = new List[V];

        for (int i = 0; i < V; i++) {

          adj[i] = new ArrayList<>();

       } }

   public void addEdge(int u, int v) {

      adj[u].add(v);

      adj[v].add(u);

   } }

   Graph graph = new Graph(4);

   graph.addEdge(0, 1);

   graph.addEdge(1, 2);

   graph.addEdge(2, 3);

  1. 字符串(String):一种由字符组成的有序序列,通常用于存储文本信息。例如:

  String str = "Hello, world!";

  System.out.println(str.charAt(0)); // 输出 H

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值