本文來自真實面試題:能說一下棧的特性嗎崭歧?棧一定得用數(shù)組才能實現(xiàn)嗎?
答案:不一定撞牢,棧既可以用數(shù)組實現(xiàn)率碾,也可以用鏈表實現(xiàn)。
下面貼上代碼:
/**
* 實現(xiàn)一個棧屋彪,用數(shù)組播掷。
* 也可以用鏈表
*/
public class ArrayStack {
private String[] items; // 棧
private int count; // 目前棧中元素個數(shù)
private int n; // 元素總數(shù)
public ArrayStack(int n) {
this.count = 0;
items = new String[n];
this.n = n;
}
// 入棧操作
public boolean push(String item) {
if(count == n) return false;
items[count++] = item;
return true;
}
// 出棧操作
public String pop() {
if(count == 0) return null;
return items[--count];
}
public static void main(String[] args) {
ArrayStack arrayStack = new ArrayStack(3);
arrayStack.push("1");
arrayStack.push("2");
arrayStack.push("3");
System.out.println(arrayStack.push("4"));
System.out.println(arrayStack.pop());
}
}
/**
* 基于鏈表實現(xiàn)的棧,棧長不限制
*/
public class LinkedListStack {
private Node head = null;
public boolean push(int item) {
Node newNode = new Node(item, null);
if (head == null) {
head = newNode;
}
newNode.next = head;
head = newNode;
return true;
}
public int pop() {
if(head ==null) return -1; // 棧為空時撼班,返回 -1
int res = head.data;
head = head.next;
return res;
}
private static class Node{
private Node next;
private int data;
public Node(int data, Node next ) {
this.data = data;
this.next = next;
}
public int getData() {
return data;
}
}
}