Java栈实现

本文探讨了Java中栈的两种常见实现:数组和单链表。栈数组实现具有快速的入栈和出栈操作(O(1)时间复杂度),但可能受限于固定长度。而栈单链表实现则无长度限制,同时保持了快速的入栈和出栈速度,时间复杂度同样为O(1)。数组实现时,若需扩容,则入栈操作的时间复杂度升至O(N)。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

栈数组实现一:优点:入栈和出栈速度快,缺点:长度有限(有时候这也不能算是个缺点)

public class Stack {
	private int top = -1;
	private Object[] objs;
	
	public Stack(int capacity) throws Exception{
		if(capacity < 0)
			throw new Exception("Illegal capacity:"+capacity);
		objs = new Object[capacity];
	}
	
	public void push(Object obj) throws Exception{
		if(top == objs.length - 1)
			throw new Exception("Stack is full!");
		objs[++top] = obj;
	}
	
	public Object pop() throws Exception{
		if(top == -1)
			throw new Exception("Stack is empty!");
		return objs[top--];
	}
	
	public void dispaly(){
		System.out.print("bottom -> top: | ");
		for(int i = 0 ; i <= top ; i++){
			System.out.print(objs[i]+" | ");
		}
		System.out.print("\n");
	}
	
	public static void main(String[] args) throws Exception{
		Stack s = new Stack(2);
		s.push(1);
		s.push(2);
		s.dispaly();
		System.out.println(s.pop());
		s.dispaly();
		s.push(99);
		s.dispaly();
		s.push(99);
	}
}
bottom -> top: | 1 | 2 | 
2
bottom -> top: | 1 | 
bottom -> top: | 1 | 99 | 
Exception in thread "main" java.lang.Exception: Stack is full!
	at Stack.push(Stack.java:17)
	at Stack.main(Stack.java:44)

数据项入栈和出栈的时间复杂度都为常数O(1)

栈数组实现二:优点:无长度限制,缺点:入栈慢

import java.util.Arrays;

public class UnboundedStack {
	private int top = -1;
	private Object[] objs;
	
	public UnboundedStack() throws Exception{
		this(10);
	}
	
	public UnboundedStack(int capacity) throws Exception{
		if(capacity < 0)
			throw new Exception("Illegal capacity:"+capacity);
		objs = new Object[capacity];
	}
	
	public void push(Object obj){
		if(top == objs.length - 1){
			this.enlarge();
		}
		objs[++top] = obj;
	}
	
	public Object pop() throws Exception{
		if(top == -1)
			throw new Exception("Stack is empty!");
		return objs[top--];
	}
	
	private void enlarge(){
		int num = objs.length/3;
		if(num == 0)
			num = 1;
		objs = Arrays.copyOf(objs, objs.length + num);
	}
	
	public void dispaly(){
		System.out.print("bottom -> top: | ");
		for(int i = 0 ; i <= top ; i++){
			System.out.print(objs[i]+" | ");
		}
		System.out.print("\n");
	}
	
	public static void main(String[] args) throws Exception{
		UnboundedStack us = new UnboundedStack(2);
		us.push(1);
		us.push(2);
		us.dispaly();
		System.out.println(us.pop());
		us.dispaly();
		us.push(99);
		us.dispaly();
		us.push(99);
		us.dispaly();
	}
}
bottom -> top: | 1 | 2 | 
2
bottom -> top: | 1 | 
bottom -> top: | 1 | 99 | 
bottom -> top: | 1 | 99 | 99 | 

由于该栈是由数组实现的,数组的长度是固定的,当栈空间不足时,必须将原数组数据复制到一个更长的数组中,考虑到入栈时或许需要进行数组复制,平均需要复制N/2个数据项,故入栈的时间复杂度为O(N),出栈的时间复杂度依然为O(1)

栈单链表实现:没有长度限制,并且出栈和入栈速度都很快

public class LinkedList {
	private class Data{
		private Object obj;
		private Data next = null;
		
		Data(Object obj){
			this.obj = obj;
		}
	}
	
	private Data first = null;
	
	public void insertFirst(Object obj){
		Data data = new Data(obj);
		data.next = first;
		first = data;
	}
	
	public Object deleteFirst() throws Exception{
		if(first == null)
			throw new Exception("empty!");
		Data temp = first;
		first = first.next;
		return temp.obj;
	}
			
	public void display(){
		if(first == null)
			System.out.println("empty");
		System.out.print("top -> bottom : | ");
		Data cur = first;
		while(cur != null){
			System.out.print(cur.obj.toString() + " | ");
			cur = cur.next;
		}
		System.out.print("\n");
	}
}
public class LinkedListStack {
	private LinkedList ll = new LinkedList();
	
	public void push(Object obj){
		ll.insertFirst(obj);
	}
	
	public Object pop() throws Exception{
		return ll.deleteFirst();
	}
	
	public void display(){
		ll.display();
	}
	
	public static void main(String[] args) throws Exception{
		LinkedListStack lls = new LinkedListStack();
		lls.push(1);
		lls.push(2);
		lls.push(3);
		lls.display();
		System.out.println(lls.pop());
		lls.display();
	}
}
top -> bottom : | 3 | 2 | 1 | 
3
top -> bottom : | 2 | 1 | 

数据项入栈和出栈的时间复杂度都为常数O(1)

关于的使用,内有关于使用的示例 的应用举例 1. 将10进制正整数num转换为n进制 private String conversion(int num, int n) { MyStack myStack = new MyArrayStack(); Integer result = num; while (true) { // 将余数入 myStack.push(result % n); result = result / n; if (result == 0) { break; } } StringBuilder sb = new StringBuilder(); // 按出的顺序倒序排列即可 while ((result = myStack.pop()) != null) { sb.append(result); } return sb.toString(); } 2. 检验符号是否匹配. '['和']', '('和')'成对出现时字符串合法. 例如"[][]()", "[[([]([])()[])]]"是合法的; "([(])", "[())"是不合法的. 遍历字符串的每一个char, 将char与顶元素比较. 如果char和顶元素配对, 则char不入, 否则将char入. 当遍历完成时为空说明字符串是合法的. public boolean isMatch(String str) { MyStack myStack = new MyArrayStack(); char[] arr = str.toCharArray(); for (char c : arr) { Character temp = myStack.pop(); // 为空时只将c入 if (temp == null) { myStack.push(c); } // 配对时c不入 else if (temp == '[' && c == ']') { } // 配对时c不入 else if (temp == '(' && c == ')') { } // 不配对时c入 else { myStack.push(temp); myStack.push(c); } } return myStack.isEmpty(); } 3. 行编辑: 输入行中字符'#'表示退格, '@'表示之前的输入全都无效. 使用保存输入的字符, 如果遇到'#'就将顶出, 如果遇到@就清空. 输入完成时将中所有字符出后反转就是输入的结果: private String lineEdit(String input) { MyStack myStack = new MyArrayStack(); char[] arr = input.toCharArray(); for (char c : arr) { if (c == '#') { myStack.pop(); } else if (c == '@') { myStack.clear(); } else { myStack.push(c); } } StringBuilder sb = new StringBuilder(); Character temp = null; while ((temp = myStack.pop()) != null) { sb.append(temp); } // 反转字符串 sb.reverse(); return sb.toString(); }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值