Java是一門(mén)廣泛應(yīng)用于軟件開(kāi)發(fā)和網(wǎng)絡(luò)編程的編程語(yǔ)言,很多開(kāi)發(fā)人員都會(huì)選擇使用Java來(lái)實(shí)現(xiàn)一個(gè)隊(duì)列數(shù)據(jù)結(jié)構(gòu)。隊(duì)列是一種數(shù)據(jù)結(jié)構(gòu),類(lèi)似于現(xiàn)實(shí)生活中的排隊(duì),它遵循先進(jìn)先出的原則。Java中可以使用數(shù)組和鏈表來(lái)實(shí)現(xiàn)一個(gè)隊(duì)列。
使用數(shù)組實(shí)現(xiàn)隊(duì)列:
public class ArrayQueue { private int[] queue; private int head; private int tail; private int size; private int capacity; public ArrayQueue(int capacity) { this.queue = new int[capacity]; this.head = 0; this.tail = 0; this.size = 0; this.capacity = capacity; } public void enqueue(int item) { if (size == capacity) { throw new RuntimeException("Queue is full"); } queue[tail] = item; tail = (tail + 1) % capacity; size++; } public int dequeue() { if (size == 0) { throw new RuntimeException("Queue is empty"); } int item = queue[head]; head = (head + 1) % capacity; size--; return item; } public boolean isEmpty() { return size == 0; } }
使用鏈表實(shí)現(xiàn)隊(duì)列:
public class LinkedListQueue { private ListNode head; private ListNode tail; private int size; public LinkedListQueue() { this.head = null; this.tail = null; this.size = 0; } public void enqueue(int item) { ListNode newNode = new ListNode(item); if (tail == null) { head = newNode; tail = newNode; } else { tail.next = newNode; tail = newNode; } size++; } public int dequeue() { if (head == null) { throw new RuntimeException("Queue is empty"); } int item = head.val; head = head.next; if (head == null) { tail = null; } size--; return item; } public boolean isEmpty() { return head == null; } private static class ListNode { private int val; private ListNode next; public ListNode(int val) { this.val = val; this.next = null; } } }
通過(guò)數(shù)組和鏈表來(lái)實(shí)現(xiàn)一個(gè)隊(duì)列數(shù)據(jù)結(jié)構(gòu),可以方便地進(jìn)行插入和刪除操作,并且可以保證數(shù)據(jù)在隊(duì)列中的先后順序。