欢迎访问宙启技术站
智能推送

使用Java函数实现数据结构:链表、栈和队列

发布时间:2023-06-10 07:10:13

Java是一种很流行的编程语言,它提供丰富的数据结构和算法库。在Java中,我们可以使用函数实现不同的数据结构比如链表、栈和队列。

链表是一种基础的数据结构,由一系列节点组成。每个节点都包含了数据和下一个节点的指针。如下是Java实现链表的代码:

public class Node {
  int data;
  Node next;

  public Node(int data) {
    this.data = data;
    this.next = null;
  }
}

public class LinkedList {
  Node head;

  public LinkedList() {
    this.head = null;
  }

  public void insert(int data) {
    Node newNode = new Node(data);

    if(this.head == null) {
      this.head = newNode;
      return;
    }

    Node current = this.head;
    while(current.next != null) {
      current = current.next;
    }

    current.next = newNode;
  }

  public void printList() {
    Node current = this.head;

    while (current != null) {
      System.out.print(current.data + "");
      current = current.next;
    }
  }
}

栈是一种后进先出的数据结构,可以用数组或链表实现。下面是使用链表实现的栈的代码:

public class Stack {
  Node head;

  public Stack() {
    this.head = null;
  }

  public void push(int data) {
    Node newNode = new Node(data);

    if (head == null) {
      head = newNode;
      return;
    }

    newNode.next = head;
    head = newNode;
  }

  public int pop() {
    if (head == null) {
      throw new EmptyStackException();
    }

    int data = head.data;
    head = head.next;
    return data;
  }
}

队列是一种先进先出的数据结构,也可以用数组或链表实现。下面是使用链表实现的队列的代码:

public class Queue {
  Node front, rear;

  public Queue() {
    this.front = this.rear = null;
  }

  public void enqueue(int data) {
    Node newNode = new Node(data);

    if (this.rear == null) {
      this.front = this.rear = newNode;
      return;
    }

    this.rear.next = newNode;
    this.rear = newNode;
  }

  public int dequeue() {
    if (this.front == null) {
      throw new NoSuchElementException();
    }

    int data = this.front.data;
    this.front = this.front.next;

    if (this.front == null) {
      this.rear = null;
    }

    return data;
  }
}

这些数据结构实现的核心是节点类的定义,以及各种操作函数的实现,比如插入、删除、打印等等。如果你需要在程序中使用这些数据结构,可以按照上面的代码进行实例化并使用相应的操作函数。