括号匹配(链表栈)

OK代表匹配成功

NO代表匹配失败

package Test;

import java.util.Iterator;

public class stack<Item> implements Iterable<Item>{

private int N;

private Node First;

private class Node{

Item item;

Node next;

}

public boolean isEmpty(){

return First==null;

}

public int size(){

return N;

}

public void insert(Item item){

Node old=First;

First=new Node();

First.item=item;

First.next=old;

N++;

}

public Item del(){

if(!isEmpty()){

Item temp=First.item;

First=First.next;

N–;

return temp;

}

return null;

}

@Override

public Iterator<Item> iterator() {

// TODO Auto-generated method stub

return null;

}

private class LinkIterator implements Iterator<Item>{

private Node temp=First;

@Override

public boolean hasNext() {

// TODO Auto-generated method stub

return temp!=null;

}

@Override

public Item next() {

// TODO Auto-generated method stub

Item item=temp.item;

temp=temp.next;

return item;

}

@Override

public void remove() {

// TODO Auto-generated method stub

}}

public static void main(String args[]){

System.out.print(A(“{(())[]}”));    

    

}

private static int A(String temp) {

stack<String> stack=new stack<String>();

char[] ch=temp.toCharArray();

for(int i=0;i<ch.length;i++){

if(ch[i]=='{‘){

   
stack.insert(“{“);

    }

 

if(ch[i]=='(‘){

   
stack.insert(“(“);

    }

if(ch[i]=='[‘){

   
stack.insert(“[“);

    }

if(ch[i]==’)’){

   
if(stack.del()!=”(“){

   
System.out.print(“No”);

   
return -1;

   
};

    }

if(ch[i]==’}’){

   
if(stack.del()!=”{“){

   
System.out.print(“No”);

   
return -1;

   
};

    }

if(ch[i]==’]’){

   
if(stack.del()!=”[“){

   
System.out.print(“No”);

   
return -1;

   
};

    }

 

}

if(stack.isEmpty())
{

System.out.print(“OK”);

return 0;

}

else{System.out.print(“No”);

return -1;}

}

}

    原文作者:括号匹配问题
    原文地址: https://blog.csdn.net/Imciandy/article/details/80390171
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞