使用栈判断输入的表达式中括号是否配对

import java.util.Scanner;

class LStack
{
    class Node
    {
        char data;
        Node next;
    }

    Node head;

    public LStack()
    {
        head = new Node();
    }

    // 进栈
    // 其实就是头插法建表,把结点插在头结点和原栈顶结点之间,并将此结点变为栈顶结点
    public void Push(char data)
    {
        Node n = new Node();
        n.data = data;
        n.next = head.next;
        head.next = n;
    }

    // 出栈
    public char Pop()
    {
        Node n = new Node();
        if (head.next == null)
            return 0;
        char a = head.next.data;
        head.next = head.next.next;
        return a;
    }

    // 显示栈中元素
    public void DispStack()
    {
        Node n = head.next;
        while (n != null)
        {
            System.out.print(n.data + " ");
            n = n.next;
        }
        System.out.println();
    }

    // 获取栈顶元素
    public char GetTop()
    {
        if (head.next == null)
            return 0;
        else
            return head.next.data;
    }

    // 获取栈的长度
    public int StackLength()
    {
        int l = 0;
        Node n = head.next;
        while (n != null)
        {
            l++;
            n = n.next;
        }
        return l;
    }
}

public class MyLStack
{
    public static void main(String args[])
    {
        Scanner cin = new Scanner(System.in);
        String str = cin.nextLine();
        System.out.println(Match(str));

    }

    public static boolean Match(String str)
    {
        LStack ls = new LStack();
        for (int i = 0; i < str.length(); i++)
        {
            if (str.charAt(i) == '(')
                ls.Push('(');
            else if (str.charAt(i) == ')')
            {
                if (ls.GetTop() == '(')
                    ls.Pop();
                else
                    return false;
            }
        }
        if (ls.StackLength() == 0)
            return true;
        else
            return false;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值