數據結構與算法分析java——棧和隊列


1. 棧

1.1 分類

  順序棧:順序線性表實現

  鏈式棧:單向鏈表存儲堆棧

 

1.2棧的應用

1)數制轉換

import java.util.Scanner;
 
import java.util.Stack;
 
public class Tran{
 
    public static void main(String arg[]){
 
     Scanner y=new Scanner(System.in);
 
     System.out.println("請輸入十進制數");
 
     int b=y.nextInt();
 
     Tran j=new  Tran();
 
     j.ErJinZhi(b);
 
     j.BaJinZhi(b);
 
     j.ShiLiuJinZhi(b);
 
    }
 
  //轉化成二進制
 
  void ErJinZhi(int a){
 
    Stack<Integer> s=new Stack<Integer>();
 
    String str="";
 
    while(a>0)
 
    {
 
     s.push(a%2);
 
     a=a/2;
 
    }
 
    while(!s.isEmpty()){
 
     str=str+s.pop();
 
    }
 
  System.out.println("二進制是"+str);
 
  } 
 
  //轉化成八進制
 
  void BaJinZhi(int a){
 
  Stack<Integer> s=new Stack<Integer>();
 
    String str="";
 
    while(a>0)
 
    {
 
     s.push(a%8);
 
     a=a/8;
 
    }
 
    while(!s.isEmpty()){
 
     str=str+s.pop();
 
    }
 
   System.out.println("八進制是"+str);
 
  }
 
  //轉化成十六進制
 
  void ShiLiuJinZhi(int a){
 
   int c=0;
 
   String str="";
 
   Stack<Character> s=new Stack<Character>();
 
   while(a>0)
 
   {
 
    c=a%16;
 
    switch(c){
 
    case(10):s.push('A');break;
 
    case(11):s.push('B');break;
 
    case(12):s.push('C');break;
 
    case(13):s.push('D');break;
 
    case(14):s.push('E');break;
 
    case(15):s.push('F');break;
 
    default:s.push((char)(a%16+48));
 
    }
 
    a=a/16;
 
   }
 
   while(!s.isEmpty()){
 
    str=str+s.pop();
 
   }
 
   System.out.println("十六進制是"+str);
 
  }
 
}
View Code

 

 

2)表達式的轉換

中綴表達式: a+b*c ;  前綴表達式: +a*bc;  后綴表達式: acb*+

 

  參考:  http://blog.csdn.net/antineutrino/article/details/6763722/

 

3)遞歸

4)遞歸的非遞歸實現

 

2. 隊列

2.1 隊列基本操作

 

2.2 順序隊列 和鏈式隊列

 

 

 

3. Stack類

import java.util.*;

public class StackDemo {

   static void showpush(Stack st, int a) {
      st.push(new Integer(a));
      System.out.println("push(" + a + ")");
      System.out.println("stack: " + st);
   }

   static void showpop(Stack st) {
      System.out.print("pop -> ");
      Integer a = (Integer) st.pop();
      System.out.println(a);
      System.out.println("stack: " + st);
   }

   public static void main(String args[]) {
      Stack st = new Stack();
      System.out.println("stack: " + st);
      showpush(st, 42);
      showpush(st, 66);
      showpush(st, 99);
      showpop(st);
      showpop(st);
      showpop(st);
      try {
         showpop(st);
      } catch (EmptyStackException e) {
         System.out.println("empty stack");
      }
   }
}

 

stack: [ ]
push(42)
stack: [42]
push(66)
stack: [42, 66]
push(99)
stack: [42, 66, 99]
pop -> 99
stack: [42, 66]
pop -> 66
stack: [42]
pop -> 42
stack: [ ]
pop -> empty stack

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM