第十一周学习知识总结

一、栈

  1. 入栈

    void push(Stack *S, ElemType e) {
      S->elem[++S->top] = e; 
      if (S->top>=S->capacity) { 
        S->elem = (ElemType *) realloc(S->elem,
    (S
    ->capacity+SEGMENT)*sizeof(ElemType)); S->capacity += SEGMENT; } }

     

  2. 出栈

    ElemType pop(Stack *S) {
      ElemType e; 
        
      if (S->top<0) return -1; 
      e = S->elem[S->top--]; 
      if (S->top<=S->capacity-SEGMENT*2) {
     
        S->elem = (ElemType *) realloc(S->elem,
                                                           (S->capacity-SEGMENT)*sizeof(ElemType));
        S->capacity -= SEGMENT;                         
      }
      return e;
    }

     

二、栈的应用——括号匹配问题

// 检查字符串 str 是否全部是全括号 '(', ')', '[', ']', '{', 或 '}'。 
int allParenthesis(char *str) {
  int i;
  for (i=0; i) 
    if (!(str[i]=='(' || str[i]==')' ||  
          str[i]=='[' || str[i]==']' ||
          str[i]=='{' || str[i]=='}')) return 0;

  return 1;  
}

// 检查两个字符是否匹配。
int isMatching(char e, char c) {

  return (e=='(' && c==')') || (e=='[' && c==']') || (e=='{' && c=='}'); } 


int parenthesisMatching(char *str) {  
  Stack S;
  char e; 
  int matching = 1; 
  int i; 
  initial(&S);
    
  for (i=0; i) {    
    if (str[i]=='(' || str[i]=='[' || str[i]=='{') 
      push(&S, str[i]); 
    else {
      e = pop(&S); 
   
      if (!isMatching(e, str[i])) matching = 0;  
    } 
  }
  if (matching==1 && is_empty(S)) matching = 1; 
  else matching = 0;  
 clear(&S); 
  return matching; 
} 

 

你可能感兴趣的:(第十一周学习知识总结)