使用栈进行括号配对

前段时间在面试的过程中被问到如何判断括号的配对问题。当时只说了大致的思路,今天闲下来实现一下

package dataStructure;

import java.util.Scanner;

public class IsMatch {
	static boolean isMatch(LLStack stack) {	
		System.out.println("请输入表达式:");
		Scanner scanner = new Scanner(System.in);
		String curString = scanner.next();
		//字符处理
		for(int i = 0; i < curString.length(); i++) {
			char ch = curString.charAt(i);
			switch(ch) {	
				case '(' :
					stack.push(ch);
					break;
				case '[' : 
					stack.push(ch);
					break;
				case '{' : 
					stack.push(ch);
					break;
				case ')' :
					if(stack.isEmpty() || stack.top() != '(' ) {
						System.out.println("匹配失败");
						return false;
					}else {
					 	stack.pop();
					}	
					break;
				case ']' :
					if(stack.isEmpty() || stack.top() != '[' ) {
						System.out.println("匹配失败");
						return false;
					}else {
					 	stack.pop();
					}
					break;
				case '}' :
					if(stack.isEmpty() || stack.top() != '{' ) {
						System.out.println("匹配失败");
						return false;
					}else {
					 	stack.pop();
					}	
					break;
				}		
			}
		//字符处理后栈非空
		if(!stack.isEmpty()) {
			System.out.println("匹配失败");
			return false;
		}		
		System.out.println("匹配成功");
		return true;
	}
	public static void main(String[] args) {
		LLStack stack = new LLStack();
		while(isMatch(stack)) {
			
		}
	}
}

使用java来实现栈

class LLNode{
	private char data;
	private LLNode next = null;
	
	public LLNode(char d){
		data = d;
	}
	public char getData() {
		return data;
	}
	public void setData(char data) {
		this.data = data;
	}
	public LLNode getNext() {
		return next;
	}
	public void setNext(LLNode next) {
		this.next = next;
	}
}
public class LLStack {
	private LLNode  head;
	
	boolean isEmpty() {
		return head == null;
	}
	
	int size() {
		int count = 1;
		LLNode cur = head;
		if(isEmpty())  return 0;
		while(cur.getNext() !=null ) {
			cur = cur.getNext();
			count++;
		}
		return count;
	}
	
	char top() {
		if(isEmpty()) 
			return 0;
		return head.getData();
	}
	
	void push(char d) {
		if(isEmpty()) {
			head =new LLNode(d);		
		}else {
			LLNode node = new LLNode(d);
			node.setNext(head);
			head = node;
		}
	}
	
	char pop() {
		if(isEmpty())
			new Exception("栈空");
		LLNode del = head;
		head = head.getNext();
		return del.getData();
	}
	void display() {
		if(isEmpty()) {
			System.out.println("栈空");
		}else {
			LLNode cur = head;
			System.out.print("栈内元素:");
			while(cur != null) {
				System.out.print(cur.getData() + "->");
				cur = cur.getNext();
			}
			System.out.println();
		}
	}
	
	void deleteStack() {
		head  = null;
	}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值