使用編譯器編譯程序時,程序出錯時編譯器會告訴我們那裏輸入有誤。程序中使用到的各種括號是否匹配是編譯器檢驗程序是否出錯的一個指標。有時候我們在程序的最後少寫了個右花括號},儘管實際只少寫了個},可能會導致編譯器報上百個錯誤。既然編譯器都有這個括號匹配功能,試試自己能否的實現括號匹配問題。爲使問題簡單化,輸入括號僅限花括號{}和方括號[]。
查過資料後,發現使用棧可以很好的解決上述的問題。開始時初始化棧爲空。當讀取左括號(見注)時,將相應的左括號壓入棧中。當讀取的是右括號時,從棧中彈出數據,並與右括號比較來檢查括號是否匹配。如果括號匹配,循環上述步驟。如果不匹配,則輸入的括號不平衡。將括號讀取完成後,檢測棧是否爲空。棧爲空則輸入的括號相平衡。否則,輸入括號不相匹配。
注:左括號爲 { [
左括號爲 } ]
代碼組織: stack.c 和stack.h -------棧的操作
main.c ---------使用棧解決問題
程序的功能實現括號的平衡。符號數據輸入爲大括號{ }或者中括號 [ ]
[root@lumotuwe] gcc main.c stack.c -o main
[root@lumotuwe] ./main [ { } ] { [ ] }
main.c
/************************************************************************
* File Name :symbol blance
* Copyright :scut,All Rights Reserved.
* Create Data :2012/11/22
* Author :lumotuwe
* Abstruct Description :[root@localhost] ./main
* [ ] ( )
*
************************************************************************/
#include<stdio.h>
#include<string.h>
#include "stack.h"
#include "stdlib.h"
int main(int argc, char ** argv)
{
int i;
Stack S;
if( (argc-1) % 2 != 0 )
{
printf( "Balance no\n" );
return 2;
}
S = CreateStack( );
for( i=1; i<argc; i++ )
{
switch ( argv[i][0] )
{
case 91 : Push( 91, S );break; //[
case 123 : Push( 123, S );break; //(
case 125 : if( Pop( S ) != 123 ) goto erro1;break;
case 93 : if( Pop( S ) != 91 ) goto erro1;break;
default : goto erro2;
}
}
if( IsEmpty( S ) )
{
printf( "Balance yes\n" );
return 0;
}
erro1:
printf( "Balance no\n" );
return 3;
erro2:
printf( "input erro,please input only""["" or"" }""\n" );
return 2;
}
stack.h
#ifndef _Satack_h
struct Node
{
int Element;
struct Node *Next;
};
typedef struct Node *PtrToNode;
typedef PtrToNode Stack;
int IsEmpty( Stack S );
Stack CreateStack( void );
void DisposeStack( Stack S );
void MakeEmpty( Stack S );
void Push( int X, Stack S );
int Top( Stack S );
int Pop(Stack S);
#endif
stack.c
#include "stack.h"
#include <stdlib.h>
#include <stdio.h>
/* Return true if S is empty*/
int IsEmpty( Stack S )
{
return S->Next == NULL;
}
/*Return the head of Stack*/
/*Retrun NULL if no memory*/
Stack CreateStack( void )
{
Stack Head;
Head=( Stack )malloc( sizeof( struct Node ) );
if (Head == NULL)
{
printf( "Out of space" );
return Head;
}
Head->Next = NULL;
return Head;
}
void DisposeStack( Stack S )
{
}
void MakeEmpty( Stack S )
{
}
void Push( int X, Stack S )
{
PtrToNode Tmp;
Tmp = ( PtrToNode ) malloc( sizeof( struct Node ) );
if( Tmp == NULL )
printf( "Out of space" );
Tmp->Next = S->Next;
S->Next = Tmp;
Tmp->Element = X;
}
int Top( Stack S )
{
}
int Pop(Stack S)
{
int data;
if( IsEmpty( S ) ) return 0;
PtrToNode Tmp = S->Next;
data = S->Next->Element;
S->Next = S->Next->Next;
free(Tmp);
return data;
}