`

栈 队列

    博客分类:
  • Java
阅读更多

下面的代码是栈的使用的简单例子,以及栈的两个应用:字符串倒置,判断括号是否匹配。

 

import java.util.Stack;

public class StackTest 
{
	private static Stack<String> stack = new Stack<String>();
	
	public static void main(String[] args)
	{			
		String[] str = new String[]{"ab", "cd", "ef", "gh"};
		Reverse(str);
		
		String word = "abcdefg";
		Reverse(word);
		
		String match = "a{B[cf(ds)kf]s}sd";
		isMatch(match);
	}
	
	public static void Reverse(String[] str)
	{
		System.out.print("Before reverse: ");
		for(int i=0; i<str.length; i++)
			System.out.print(str[i] + " ");	
		
		for(int i=0; i<str.length; i++)
			stack.push(str[i]);
			
		System.out.println();
		System.out.print("After  reverse: ");
		while(!stack.isEmpty())
			System.out.print(stack.pop() + " ");
		System.out.println();
	}
	
	public static void Reverse(String str)
	{
		System.out.print("Before reverse: ");
		System.out.print(str);
		
		for(int i=0; i<str.length(); i++)
			stack.push(String.valueOf(str.charAt(i)));
		
		System.out.println();
		System.out.print("After  reverse: ");
		while(!stack.isEmpty())
			System.out.print(stack.pop());
		System.out.println();
	}
	
	public static void isMatch(String str)
	{
		char ch;
		String temp;
		String top;
		boolean flag = true;
		
		for(int i=0; i<str.length(); i++)
		{
			ch = str.charAt(i);
			temp = String.valueOf(ch);
			
			if(temp.equals("{") || temp.equals("[") || temp.equals("("))
				stack.push(String.valueOf(ch));
			else if(temp.equals("}") || temp.equals("]") || temp.equals(")"))
			{
				if(stack.isEmpty())
				{
					flag = false;
					System.out.println("Not match !");
					break;
				}
				else
				{
					top = stack.pop();
					if((top.equals("{") && !temp.equals("}")) || (top.equals("[") && !temp.equals("]")) || (top.equals("(") && !temp.equals(")")))
					{
						stack.push(top);
						System.out.println("Not match !");
						break;
					}
				}
			}
		}
		
		if(stack.isEmpty() && flag)
			System.out.println("Match!");
	}
}

/**
 * 输出如下:
 * Before reverse: ab cd ef gh 
   After  reverse: gh ef cd ab 
   Before reverse: abcdefg
   After  reverse: gfedcba
   Match!
 */

 

 

下面的代码是队列的简单使用。

 

public class QueueTest 
{
	public static void main(String[] args)
	{
		String[] str = new String[]{"ab", "cd", "ef", "gh"};
		
		Queue<String> queue = new LinkedList<String>();
		
		Display(str, queue);
	}
	
	public static void Display(String[] str, Queue<String> queue)
	{
		for(int i=0; i<str.length; i++)
			queue.add(str[i]);
		
		while(!queue.isEmpty())
			System.out.print(queue.poll() + " ");
		System.out.println();
	}
}

/**
 * 输出如下:
 * ab cd ef gh
 */

 

2
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics