您的位置:首页 > 其它

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

2015-11-10 15:14 267 查看
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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: