Java中常用的數(shù)據(jù)結(jié)構(gòu)有棧和隊(duì)列,它們有著廣泛的應(yīng)用場(chǎng)景,例如算法實(shí)現(xiàn)、數(shù)據(jù)處理、網(wǎng)絡(luò)編程等。以下是Java棧和隊(duì)列的代碼實(shí)現(xiàn)。
// Java棧的實(shí)現(xiàn) public class Stack { private int[] arr; private int top; // 構(gòu)造函數(shù),創(chuàng)建一個(gè)空棧 public Stack(int size) { arr = new int[size]; top = -1; } // 進(jìn)棧 public void push(int data) { if (top == arr.length - 1) { throw new RuntimeException("Stack is full."); } arr[++top] = data; } // 出棧 public int pop() { if (top == -1) { throw new RuntimeException("Stack is empty."); } return arr[top--]; } // 查看棧頂元素 public int peek() { if (top == -1) { throw new RuntimeException("Stack is empty."); } return arr[top]; } // 判斷棧是否為空 public boolean isEmpty() { return top == -1; } } // Java隊(duì)列的實(shí)現(xiàn) public class Queue { private int[] arr; private int front; private int rear; // 構(gòu)造函數(shù),創(chuàng)建一個(gè)空隊(duì)列 public Queue(int size) { arr = new int[size]; front = 0; rear = -1; } // 進(jìn)隊(duì) public void enqueue(int data) { if (rear == arr.length - 1) { throw new RuntimeException("Queue is full."); } arr[++rear] = data; } // 出隊(duì) public int dequeue() { if (front >rear) { throw new RuntimeException("Queue is empty."); } return arr[front++]; } // 查看隊(duì)頭元素 public int peek() { if (front >rear) { throw new RuntimeException("Queue is empty."); } return arr[front]; } // 判斷隊(duì)列是否為空 public boolean isEmpty() { return front >rear; } }